0
点赞
收藏
分享

微信扫一扫

linux之shell快速入门系列<6> | shell函数的使用

龙驹书房 2022-03-19 阅读 72

shell函数的使用

文章目录

1、系统函数

basename
基本语法

功能:

选项:

操作案例:

  1. 不加stuffix后缀选项
    [root@bigdata01 centos-shell]# basename /opt/module/hadoop-2.7.2/etc/hadoop/yarn-site.xml
    yarn-site.xml
    
  2. 加上suffix选项
    [root@bigdata01 centos-shell]# basename /opt/module/hadoop-2.7.2/etc/hadoop/yarn-site.xml .xml
    yarn-site
    

dirname
基本语法

功能:

案例操作:

  1. 返回Hadoop中yarn-site.xml所在的路径
    [root@bigdata01 centos-shell]# dirname /opt/module/hadoop-2.7.2/etc/hadoop/yarn-site.xml
    /opt/module/hadoop-2.7.2/etc/hadoop
    

2、自定义函数

  1. 基本语法

  2. 经验技巧

  3. 操作案例

    1. 计算两个输入参数的和
      不使用return返回值

      [root@bigdata01 centos-shell]# chmod 777 func1.sh
      #! /bin/bash
      
      function sum()
      {
              s=0
              s=$[ $1 + $2 ]
              echo "$s"
      }
      read -t 7 -p "Please input the num1:" num1;
      read -t 7 -p "Please input the num2:" num2
      sum $num1 $num2
      
      [root@bigdata01 centos-shell]# ./func1.sh
      Please input the num1:12
      Please input the num2:56
      68
      
    2. 使用return结束并返回函数的计算结果
      使用**$?**接受函数返回的结果

      [root@bigdata01 centos-shell]# vi func2.sh
      #! /bin/bash
      function sum()
      {
              s=0
              s=$[ $1 + $2 ]
              return $s
      }
      read -t 7 -p "Please input the num1:" num1;
      read -t 7 -p "Please input the num2:" num2
      sum $num1 $num2
      echo "$?"
      
      [root@bigdata01 centos-shell]# chmod 777 func2.sh
      [root@bigdata01 centos-shell]# ./func2.sh
      Please input the num1:12
      Please input the num2:57
      69
      


举报

相关推荐

0 条评论