for循环

[size=large]以一道练习题为例子
1.编写一个if命令的语句:
判断某个用户是否存在于/etc/passwd文件
如果存在打印输出Found $USER in the /etc/passwd
如果不存在打印no such user on my system

这里读取/etc/passwd文件,然后进行判断是否存在用户,这个文件里面肯定不止一个用户,那么就要进行循环读取了,要使用循环命令
for variable in word_list
do
commands
done
相对于while,until的循环方式是必须要符合某个条件的状态,for这种语法是已经知道要进行几次循环的状态。
脚本
#!/bin/bash
FILE=/etc/passwd
name=patrol
for i in `cat $FILE`
do
USER=`echo $i |awk -F: '{print $1}'`
if [ "$USER" = "$name" ]
then
echo "Found $USER in the /etc/passwd"
exit 0 #找到这个账号就退出这个脚本
fi
done
echo "no such user on my system"
这里的awk命令可以改为
USER=`echo $i |cut -d : -f1` 也行

这里的for i in `cat $FILE`是按空格或者换行来读取$FILE文件的,写了个测试脚本
建立一个文件
# more name
ahao ahaoge
ahaogege
再写个测试脚本
# more test.sh
#!/bin/bash
file=/home/ahaoge/haha/name
for i in `cat $file`
do
echo "hello $i"
done
输出结果为
# ./test.sh
hello ahao
hello ahaoge
hello ahaogege

可见这里空格或者换行都作为list中的其中一个值。
[color=red]如果加上双引号的话,这里的单词就不会分离了[/color]

#!/bin/bash
file=/home/ahaoge/haha/name
for i in "`cat $file`"
do
echo "hello $i"
done
结果会是这样
# ./test.sh
hello ahao ahaoge
ahaogege
完整的'list'作为一个变量都封在""中
[/size]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值