[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]
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]