shell中函数的定义
1.shell中定义函数的方式:
示例1:funtion name {
command1
command2
....
}
示例2:name () {
command1
command2
...
}
取消函数:unset -f +函数名
2.向函数中传递参数:
示例:
#!/bin/bash
test ()
{
a=$1
echo "test (): \$0 is $0"
echo "test (): \$1 is $1"
echo "test (): \$a is $a"
echo "test (): total args give to me $#"
echo "test (): all args \$* give to me $*"
}
test one #调用函数,并向函数中传递一个参数one
test one tow three #调用函数,并向函数中传递三个参数one tow three
3.在函数中定义本地变量,只在函数内部生效:
使用local命令可以在函数内部定义变量,且只在函数内部生效
示例:#!/bin/bash
a=/etc/passwd
local_test () {
local a=$1 #使用local命令定义本地变量
echo "local_test():a is set to $a"
}
echo "before calling local_test a is set to $a" #调用函数前输出一次$a
local_test /var/log/secure
echo "after calling local_test a is set to $a" #调用函数后输出一次$a,两次输出的$a相同,说明函数调用后a的值未变
4.函数的返回值:
示例:
#!/bin/bash
checkpid () { #定义一个函数,判断给定的pid,对应的进程是否在运行
local i
for i in $*
do
if [[ -d "/proc/$*" ]];then #在Linux中,如果进程正在运行,则在/proc目录下会存在一个以进程号命名的子目录
return 0 #如果进程在运行则返回0,函数不再向下进行,并且返回到shell脚本中调用函数位置的下一个命令
fi
done
return 1 #如果最终没有检测到在运行的进程,函数结束,返回1
}
for a in $* #遍历用户给定的位置参数
do
checkpid $a #调用checkpid函数,检查对应的进程是否在运行
if [ $? -eq 0 ];then #根据函数的返回值做判断
echo "the pid $a existed"
else
echo "the pid $a not existed "
fi
done
5.函数的调用:
示例1:在脚本中调用函数
#!/bin/bash
yday ( ) {
date -d "3 days ago"
}
yday #在脚本中直接调用函数(函数必须要先定义再调用)
示例2:从函数文件中调用函数
第一步:定义一个函数文件
#!/bin/bash
declare -r TRUE=0
declare -r FALSE=1
declare -r PASSWD_FILE=/etc/passwd
to_lower ( ) { #定义一个函数,将参数转换为小写
local str="$*"local output=`tr '[A-Z]' '[a-z]'<<< $str`
echo $output
}
is_root ( ) { #定义一个函数,判断当前用户是否为root
ID=`id -u`if [ $ID -eq 0 ];then
return $TRUE
else
return $FALSE
fi
}
is_user_exits ( ) { #定义一个函数,判断给定的用户是否存在
local u=$1
grep "$u" $PASSWD_FILE &> /dev/null
if [ $? -eq 0 ];thenreturn $TRUE
else
return $FALSEfi
}
第二步:在脚本中调用函数
#!/bin/bash
. /root/shell/myfunction.sh #从函数的绝对路径调用函数
var="HELLO WORLD"
is_root && echo "this root" || echo "not root" #判断当前用户是否为root
is_user_exits "damao" && echo "account found" || echo "account not found" #判断用户damao是否存在
echo -e "original quote :\n$var"
echo -e "lower version :\n`to_lower $var`" #将变量var的值转换成小写
6.将函数放入后台执行:
示例:
#!/bin/bash
jindu ( ) { #定义一个进度条,每5秒输出一个..
echo -n "$0: please wait..."
while true
do
echo -n ".."
sleep 5
done
}
backup ( ) { #定义一个函数,对/root/目录做备份
tar -zcvf /data/root.tar.gz /root/* &>/dev/null
}
jindu & #调用jindu函数放入后台
Pid=$! #将进度函数的进程号复制给变量Pid
backup #调用backup函数进行备份kill $Pid &>/dev/null #备份结束后杀死jindu函数的进程
echo -n "done" #不换行输出一个done
echo #输出一个换行符