shell函数的使用
文章目录
1、系统函数
basename
基本语法
功能:
选项:
操作案例:
- 不加stuffix后缀选项
[root@bigdata01 centos-shell]# basename /opt/module/hadoop-2.7.2/etc/hadoop/yarn-site.xml yarn-site.xml
- 加上suffix选项
[root@bigdata01 centos-shell]# basename /opt/module/hadoop-2.7.2/etc/hadoop/yarn-site.xml .xml yarn-site
dirname
基本语法
功能:
案例操作:
- 返回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、自定义函数
-
基本语法
-
经验技巧
-
操作案例
-
计算两个输入参数的和
不使用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
-
使用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
-