【www.bbyears.com--linux】
shift命令声明格式: shift [n]
shift命令用来把脚本的位置参数列表向左移动指定的位数(n),如果shift没有参数,则将参数列表向左移动一位。一旦移位发生,被移出列表的参数就被永远删除了。通常在while循环中,shift用来读取列表中的参数变量。
见如下示例脚本:
/> set stephen ann sheryl mark #设置4个参数变量。
/> shift #向左移动参数列表一次,将stephen移出参数列表。
/> echo $*
ann sheryl mark
/> shift 2 #继续向左移动两位,将sheryl和ann移出参数列表
/> echo $*
mark
/> shift 2 #继续向左移动两位,由于参数列表中只有mark了,因此本次移动失败。
/> echo $*
mark
/> cat > test4.sh
while (( $# > 0 )) #等同于 [ $# -gt 0 ]
do
echo $*
shift
done
CTRL+D
/> . ./test4.sh a b c d e
a b c d e
b c d e
c d e
d e
e
break命令声明格式:break [n]
和C语言不同的是,Shell中break命令携带一个参数,即可以指定退出循环的层数。如果没有指定,其行为和C语言一样,即退出最内层循环。如果指定循环的层数,则退出指定层数的循环体。如果有3层嵌套循环,其中最外层的为1,中间的为2,最里面的是3。
见如下示例脚本:
while true
do
echo -n "Are you ready to move on?"
read answer
if [[ $answer == [Yy] ]]
then
break
else
echo "Come on."
fi
done
echo "Here we are."
CTRL+D
/> . ./test5.sh
Are you ready to move on? y
Here we are
continue命令声明格式:continue [n]
和C语言不同的是,Shell中continue命令携带一个参数,即可以跳转到指定层级的循环顶部。如果没有指定,其行为和C语言一样,即跳转到最内层循环的顶部。如果指定循环的层数,则跳转到指定层级循环的顶部。如果有3层嵌套循环,其中最外层的为3,中间的为2,最里面的是1。
/> cat maillist #测试数据文件maillist的内容为以下信息。
stephen
ann
sheryl
mark
/> cat > test6.sh
for name in $(cat maillist)
do
if [[ $name == stephen ]]; then
continue
else
echo "Hello, $name."
fi
done
CTRL+D
/> . ./test6.sh
Hello, ann.
Hello, sheryl.
Hello, mark.