shell函数,完成特定功能的代码片段(代码模块化)。函数必须先定义,然后才能使用。
shell函数的定义:
方法一: 函数名() {
函数要实现的功能代码
}
方法二:function 函数名 {
函数要实现的功能代码
}
shell函数的调用:
函数名
函数名 参数1 参数2
[root@a ~]#cat fun.txt #定义函数库文件,方便在别的地方使用
addnum1() {
echo $[$1+$2]
}
addnum2(){
echo $[$1*$2]
}
deluser(){
userdel -r $user
}
[root@a ~]#pwd
/scripts/day2/
[root@a ~]#cat test.sh
#!/bin/bash
source /scripts/day2/fun.txt #脚本中引用函数文件
#source ./fun.txt #相对路径方式
#. ./fun.txt #相对路径方式,其中.相当于source
read -p "del user: " user
deluser #调用函数
addnum1 4 5 #调用函数
addnum2 24 3 #调用函数
[root@a ~]#sh test.sh #执行测试脚本
del user: abc
9
72
[root@a ~]#id abc #查看测试结果
id: abc: no such user