Shell循环

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]# 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

春侨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值