shift命令用于跳转到下一个参数,使函数或者控制语句对于参数的处理更加灵活,
而不局限于使用$1、$2、$3、$4、$5、$6这种方式去表示参数。
下面是一个while循环,此循环的目的是读取并打印所有输入的参数。
pg readparm
#!/bin/ksh
# opt1
while [ $# -ne 0 ]
do
echo $1
done
但是这个并不能实现我们打印输入参数的目的,因为无法读取到下一个参数,
永远读取第一个,也就是说这是一个死循环。
若要跳转到下一个参数,使用shift命令去实现,如下:
pg shift_test
#!/bin/ksh
# shift_test
I=0
ORDER=""
while [ $# -ne 0 ]
do
I=`expr $I + 1`
case $I in
1) ORDER="first" ;;
2) ORDER="second";;
3) ORDER="third";;
4) ORDER="forth";;
5) ORDER="fifth";;
6) ORDER="sixth";;
7) ORDER="seventh";;
8) ORDER="eighth";;
9) ORDER="ninth";;
*) ORDER="next" ;;
esac
echo "the $ORDER parameter is $1"
# ★
shift
done
执行结果如下:
sh shift_test chenlinbo@163.com yeexun csdn
the first parameter is chenlinbo@163.com
the second parameter is yeexun
the third parameter is csdn
--the end--
而不局限于使用$1、$2、$3、$4、$5、$6这种方式去表示参数。
下面是一个while循环,此循环的目的是读取并打印所有输入的参数。
pg readparm
#!/bin/ksh
# opt1
while [ $# -ne 0 ]
do
echo $1
done
但是这个并不能实现我们打印输入参数的目的,因为无法读取到下一个参数,
永远读取第一个,也就是说这是一个死循环。
若要跳转到下一个参数,使用shift命令去实现,如下:
pg shift_test
#!/bin/ksh
# shift_test
I=0
ORDER=""
while [ $# -ne 0 ]
do
I=`expr $I + 1`
case $I in
1) ORDER="first" ;;
2) ORDER="second";;
3) ORDER="third";;
4) ORDER="forth";;
5) ORDER="fifth";;
6) ORDER="sixth";;
7) ORDER="seventh";;
8) ORDER="eighth";;
9) ORDER="ninth";;
*) ORDER="next" ;;
esac
echo "the $ORDER parameter is $1"
# ★
shift
done
执行结果如下:
sh shift_test chenlinbo@163.com yeexun csdn
the first parameter is chenlinbo@163.com
the second parameter is yeexun
the third parameter is csdn
--the end--