循环结构
1、for命令
基本格式:
for var in list
do
commands
done
#或者
for var in list;do
commands
done
-
读取列表中的值
#!/bin/bash for test in Alabama Alaska Arizona Arkansas California Colorado do echo "The next state is $test" done echo "The last state is $test" test=California echo "now we're visited is $test" ###########运行结果 [root@server ~]# sh test1.sh The next state is Alabama The next state is Alaska The next state is Arizona The next state is Arkansas The next state is California The next state is Colorado The last state is Colorado now we're visited is California
-
读取列表中的复杂值
#!/bin/bash for test in I don\'t know if "this'll" work "New York" do echo "word:$test" done ################ [root@server ~]# sh test2 word:I word:don't word:know word:if word:this'll word:work word:New York
当列表中的值有单引号时,你可以使用转义字符(反斜线)来将单引号转义,也可以使用双引号来定义用到的单引号的值。因为for循环假定每个值都是用空格分割的,所以如果有包含空格的数据值,必须用双引号括起来。
-
从变量读取列表
#!/bin/bash list="Alabama Alaska Arizona Arkansas California Colorado" list=$list" Connecticut" for state in $list do echo "Have you ever visited $state?" done [root@server ~]# sh test4.sh Have you ever visited Alabama? Have you ever visited Alaska? Have you ever visited Arizona? Have you ever visited Arkansas? Have you ever visited California? Have you ever visited Colorado? Have you ever visited Connecticut?
-
从命令读取值
生成列表中所需值的另外一个途径就是使用命令的输出。可以用命令替换来执行任何能产生输出的命令,然后再for循环中使用该命令的输出。
#!/bin/bash file="states" for state in $(cat $file) do echo "Visit beauutiful $state" done
-
更改字段分隔符
有一个特殊的环境变量IFS,叫做内部字段分隔符,IFS环境变量定义了bash shell用作字段分隔符的一系列字符。默认情况下,bash shell会将下列字符当作字段分隔符:空格、制表符、换行符。
如果你想修改IFS的值,使其只能识别换行符,那就必须这样做:
IFS=$'\n'
如果要指定多个IFS字符,只要将他们再复制行串起来就行。
IFS=$'\n':;"
,这个赋值会将换行符、冒号、分号和双引号作为分隔符。#!/bin/bash file="state" IFS.OLD=$IFS IFS=$'\n' for state in $(cat $file) do echo "Visit beautifule $state" done IFS=IFS.OLD
-
用通配符读取目录
可以用for命令来自动遍历目录中的文件。进行此操作时,必须在文件名或路径名中使用通配符。它或强制shell使用文件匹配扩展。
#!/bin/bash for file in /root/test do if [ -d file ] then echo "$file is directory" elif [ -f file ] then echo "$file is file" fi done