shell编程之带参数的函数
1.位置参数在shell中,向函数传递参数是使用位置参数来实现的。例如:[root@node1 ~]# cat checkFileExists_v2.shfunction checkFileExists(){if [ -f $1 ];thenreturn 0elsereturn 1fi}echo "Call function checkFileExists"checkFileExistsif [
·
1.位置参数
在shell中,向函数传递参数是使用位置参数来实现的。例如:
[root@node1 ~]# cat checkFileExists_v2.sh
function checkFileExists(){
if [ -f $1 ];then
return 0
else
return 1
fi
}
echo "Call function checkFileExists"
checkFileExists
if [ $? -eq 0 ];then
echo "$1 exist"
else
echo "$1 not exist"
fi
[root@node1 ~]# sh checkFileExists_v2.sh /var/log/messages
Call function checkFileExists
/var/log/messages exist
2.指定位置参数的值
除了在脚本运行时传入位置参数外,还可通过内置命令set命令给脚本指定位置参数,一旦使用set设置了传入参数的值,脚本将忽略运行时传入的位置参数,实际上是被set命令重置了位置参数的值。例如:
[root@node1 ~]# cat set.sh
#!/bin/bash
set 1 2 3 4 5 6
count=1
for i in $@
do
echo "here \$$count is $i"
let "count++"
done
[root@node1 ~]# sh set.sh a s d
here $1 is 1
here $2 is 2
here $3 is 3
here $4 is 4
here $5 is 5
here $6 is 6
3.移动位置参数
在shell中,使用shift命令移动位置参数。shift命令不带参数时,左移一位;shift 2移动两位。
[root@node1 ~]# cat shift_01.sh
#!/bin/bash
until [ $# -eq 0 ]
do
echo "Now \$1 is: $1,total parameter is : $#"
shift
done
[root@node1 ~]# sh shift_01.sh 1 2 4 5 7
Now $1 is: 1,total parameter is : 5
Now $1 is: 2,total parameter is : 4
Now $1 is: 4,total parameter is : 3
Now $1 is: 5,total parameter is : 2
Now $1 is: 7,total parameter is : 1
可将shift改为shift 2
[root@node1 ~]# cat shift_01.sh
#!/bin/bash
until [ $# -eq 0 ]
do
echo "Now \$1 is: $1,total parameter is : $#"
shift 2
done
[root@node1 ~]# sh shift_01.sh 1 2 3 4
Now $1 is: 1,total parameter is : 4
Now $1 is: 3,total parameter is : 2
也可用shift实现求和。
[root@node1 ~]# cat shift_02.sh
#!/bin/bash
total=0
until [ $# -eq 0 ]
do
let "total=total+$1"
shift
done
echo $total
[root@node1 ~]# sh shift_02.sh 1 2 3 4
10
更多推荐
已为社区贡献11条内容
所有评论(0)