简介
可以使用函数来组织一组命令变成一个完成特定任务的命令,shell在运行时,会检查函数的语法,但是只有在调用时才会运行,可以在函数内部改变函数外的变量值来达到返回值。
#!/bin/sh
# define function
add_a_user()
{
# $1、$2...将是定义的函数在使用时传入的参数
USER=$1
PASSWORD=$2
shift; shift;
COMMENT=$@
echo "Adding user $USER ($COMMENT) with $PASSWORD"
useradd -c "$COMMENT" $USER
passwd $USER $PASSWORD
a=2
}
# a is script first arg
a=$1
# use the function
add_a_user bob simplepasswd Bob Holness the presenter
add_a_user fred badpassword Fred Durst the singer
add_a_user bilko worsepassword Sgt. Bilko the role modelSgt. Bilko the role model
# a is now 2
echo $a
变量作用域
$ cat test.sh
#!/bin/sh
myfunc()
{
echo "I was called as : $@"
x=2
}
echo "Script was called with $@"
x=1
echo "x is $x"
myfunc 1 2 3
echo "x is $x"
$ chmod a+x test.sh
$ ./test.sh a b c
Script was called with a b c
x is 1
I was called as : 1 2 3
x is 2
函数可以在sub-shell
中执行,此时需要注意,函数是在另一个进程中运行!例如myfunc 1 2 3 | tee out.log
,会打开另一个shell运行此命令,此时原shell中的x
将不会被改变,所以x=1
。
退出码
return
用于返回函数的退出码,此退出码可以在稍后运行函数后,通过$?
获得。
#!/bin/sh
adduser()
{
USER=$1
PASSWORD=$2
shift ; shift
COMMENTS=$@
useradd -c "${COMMENTS}" $USER
if [ "$?" -ne "0" ]; then
echo "Useradd failed"
return 1
fi
passwd $USER $PASSWORD
if [ "$?" -ne "0" ]; then
echo "Setting password failed"
return 2
fi
echo "Added user $USER ($COMMENTS) with pass $PASSWORD"
}
## Main script starts here
adduser bob letmein Bob Holness from Blockbusters
ADDUSER_RETURN_CODE=$?
if [ "$ADDUSER_RETURN_CODE" -eq "1" ]; then
echo "Something went wrong with useradd"
elif [ "$ADDUSER_RETURN_CODE" -eq "2" ]; then
echo "Something went wrong with passwd"
else
echo "Bob Holness added to the system."
fi
编写库
$ cat rename.lib
# common.lib
# 注意由于它是一个库,所以不需要#!/bin/sh来派生一个额外的shell
#
STD_MSG="About to rename some files..."
rename()
{
# expects to be called as: rename .txt .bak
FROM=$1
TO=$2
for i in *$FROM
do
j=`basename $i $FROM`
mv $i ${j}$TO
done
}
$ cat use.sh
#!/bin/sh
# 运行库文件,导入库中的变量和函数
source ./rename.lib
echo $STD_MSG
rename .txt .bak