簡(jiǎn)介
可以使用函數(shù)來(lái)組織一組命令變成一個(gè)完成特定任務(wù)的命令,shell在運(yùn)行時(shí)时甚,會(huì)檢查函數(shù)的語(yǔ)法臊旭,但是只有在調(diào)用時(shí)才會(huì)運(yùn)行营袜,可以在函數(shù)內(nèi)部改變函數(shù)外的變量值來(lái)達(dá)到返回值路捧。
#!/bin/sh
# define function
add_a_user()
{
# $1关霸、$2...將是定義的函數(shù)在使用時(shí)傳入的參數(shù)
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
函數(shù)可以在sub-shell
中執(zhí)行,此時(shí)需要注意鬓长,函數(shù)是在另一個(gè)進(jìn)程中運(yùn)行谒拴!例如myfunc 1 2 3 | tee out.log
,會(huì)打開(kāi)另一個(gè)shell運(yùn)行此命令涉波,此時(shí)原shell中的x
將不會(huì)被改變,所以x=1
炭序。
退出碼
return
用于返回函數(shù)的退出碼啤覆,此退出碼可以在稍后運(yùn)行函數(shù)后,通過(guò)$?
獲得惭聂。
#!/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
編寫(xiě)庫(kù)
$ cat rename.lib
# common.lib
# 注意由于它是一個(gè)庫(kù)窗声,所以不需要#!/bin/sh來(lái)派生一個(gè)額外的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
# 運(yùn)行庫(kù)文件,導(dǎo)入庫(kù)中的變量和函數(shù)
source ./rename.lib
echo $STD_MSG
rename .txt .bak