文章目录函数能为我们编写脚本减轻非常大的麻烦,减少我们代码的重复,强大我们的功能。
shell函数的使用1、系统函数2、自定义函数
1、系统函数
basename
基本语法
basename [string / pathname] [suffix]
功能:
basename命令会删掉所有的前缀包括最后一个(‘/’)字符,然后将字符串显示出来,常用于返回问价名。
选项:
suffix为后缀,如果suffix被指定了,basename会将pathname或string中的suffix去掉。
操作案例:
- 不加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
基本语法
dirname 文件绝对路径
功能:
basename命令返回完整路径最后( “/ ”)的前面的部分,常用于返回路径部分
案例操作:
- 返回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
基本语法
[ function ] funname[()]
{
Action;
[return int;]
}
funname
经验技巧
(1)必须在调用函数地方之前,先声明函数,shell脚本是逐行运行。不会像其它语言一样先编译。
(2)函数返回值,只能通过$?系统变量获得,可以显示加:return返回,如果不加,将以最后一条命令运行结果,作为返回值。return后跟数值n(0-255)
操作案例
计算两个输入参数的和
不使用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
其他的shell自定义函数,也是相同的编写方法,注意的是方法一定要写在调用执行语句之前。前路漫漫,努力不间断,继续加油,铁子们



