更多的结构化命令
for命令格式: for var in list do commands done 1. 读取列表中的值读取for命令自身中定义的一系列值: for test in Mess1 Mess2 Mess3 do echo The next stat is $test done # the output will be: the next stat is Mess1 the next stat is Mess2 ... 2. 读取列表中的复杂值
3. 从变量读取列表list="hi1 hi2 hi3" list=$list" hi4" #向list尾部添加文本 for test in $list 4. 从命令读取值即:使用反引号来执行任何能产生输出的命令,然后在for命令中使用该命令的输出: for state in `cat $file` 字段分隔符Linux中有一个特殊的环境变量IFS,称为 默认情况下 IFS的值为:
我们可以修改IFS的值来修改字段分隔符。 IFS_OLD=$IFS IFS="n" <some code> IFS=IFS_OLD C语言风格的for命令
while命令格式: while test command do other commands done #!/bin/bash
# 使用多个测试命令
# 在每次迭代中,所有的测试命令都会执行;
# 每个测试命令都在单独的一行上
var1=10
while echo $var1
[ $var1 -ge 0 ]
do
echo "this is inside the loop"
done
until 语句格式: until test commands do other commands done 类似于while语句,可以在until命令中有多个测试命令 #!/bin/bash
var1=100
until echo $var1
[ $var1 -eq 0 ]
do
echo Inside the loop: $var1
var1=$[ $var1 - 25 ]
done
嵌套循环#!/bin/bash
for (( a=1; a<=3; a++ ))
do
echo "starting loop $a:"
for (( b=1; b<=3; b++ ))
do
echo "Inside loop: $b"
done
done
循环处理文件数据处理/etc/passwd文件中的数据: #!/bin/bash
# change the IFS value
IFS.OLD=$IFS
IFS="n"
for entry in `cat /etc/passwd`
do
echo "values in $entry -"
IFS=:
for value in $entry
do
echo " $value"
done
done
控制循环
处理循环的输出在shell脚本中,你要么 for file in /home/* do if [ -d "$file" ] then echo "$file is a file." fi done > output.txt shell会将结果重定向到文件output.txt中,而不是显示在屏幕上。 同样,可以将循环的结果管接给另一个命令: 脚本 test2.sh: 运行结果: 可以看出,for命令的输出传给了sort命令,他会改变for命令输出结果的顺序。 运行这个脚本实际上说明了结果已经在脚本内部排好序了。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |