8.1 for命令
for命令可以执行指定次数的一个或多个命令。其基本格式如下:
for var in word1 word2 ... wordn
do
command
command
...
done
例如:
for i in 1 2 3
do
echo $i
done
8.1.1 $@变量
为了查看出效果,首先创建一个args Shell脚本文件,
[root@centos7_c1 linux]# cat args
echo Number of arguments passed is $#
for arg in $*
do
echo $arg
done
[root@centos7_c1 linux]#
运行查看效果
[root@centos7_c1 linux]# ./args a b c
Number of arguments passed is 3
a
b
c
[root@centos7_c1 linux]# ./args 'a b' c
Number of arguments passed is 2
a
b
c
[root@centos7_c1 linux]#
第一次运行没有疑问,可第二次我们在a b上加上引号,成了两个参数,还是输出3次,why?
这是因为shell会使用a b c将for命令中的
∗
替
换
,
同
时
丢
弃
引
号
。
为
了
解
决
这
个
问
题
,
我
们
引
入
一
个
特
殊
变
量
:
*替换,同时丢弃引号。为了解决这个问题,我们引入一个特殊变量:
∗替换,同时丢弃引号。为了解决这个问题,我们引入一个特殊变量:@。
我们修改一下args脚本。用cat命令查看修改后内容:
[root@centos7_c1 linux]# cat args
echo Number of arguments passed is $#
for arg in "$@"
do
echo $arg
done
[root@centos7_c1 linux]#
之前的
∗
现
在
改
成
"
* 现在改成 "
∗现在改成"@" 了(注意不要漏了引号,如果没有引号,该变量的效果和$*没有差别)。
运行查看效果:
[root@centos7_c1 linux]# ./args a b c
Number of arguments passed is 3
a
b
c
[root@centos7_c1 linux]# ./args 'a b' c
Number of arguments passed is 2
a b
c
[root@centos7_c1 linux]#
阔以。
8.1.2 不实用列表的for命令
在使用for命令的时候,shell还能够识别一种特殊的写法。如果你忽略in以及后续的列表:
for var
do
command
command
...
done
shell自动遍历命令行中输入的所有参数,就像上面介绍过的格式一样:
for var in "$@"
do
command
command
...
done
注意是
for var in "$@"
而不是
for var in $*
8.2 while命令
while循环命令的一般格式为:
while commandt
do
command
command
...
done
例子:
[root@centos7_c1 linux]# cat twhile
i=1
while [ "$i" -le 5 ]
do
echo $i
i=$((i + 1))
done
[root@centos7_c1 linux]# ./twhile
1
2
3
4
5
[root@centos7_c1 linux]#
实用情景:while经常和shift(移动变量)搭配使用,用于处理命令行中数量不定的参数。上例子:
[root@centos7_c1 linux]# cat prargs
#
#打印出命令行参数,一行一个
#
while [ "$#" -ne 0 ]
do
echo "$1"
shift
done
[root@centos7_c1 linux]# ./prargs a b c
a
b
c
[root@centos7_c1 linux]# ./prargs 'a b' c
a b
c
[root@centos7_c1 linux]#
8.3 until命令
和while命令相反,只要测试表达式返回假,都会不停地执行代码块,直到真为止。
until的一个格式如下:
until commandt
do
command
command
...
done
接下来给出一个等待用户登录的例子:
[root@centos7_c1 linux]# cat waitfor
#
#等待指定用户登录
#
if [ "$#" -ne 1 ]
then
echo "Usage: waitfor user"
exit 1
fi
user="$1"
#
#每60秒检查一次登录状态
#
until who | grep "^$user " > /dev/null
do
sleep 60
done
#
#运行到这里说明用户已经登录
#
echo "$user has logged on"
[root@centos7_c1 linux]#