bash shell提供了for命令,用於建立經過一系列值重複的循環。每次重複使用系列中的一個值執行一個定義的命令集。shell
for命令基本格式爲:bash
for var in listide
do spa
commandsit
doneclass
1.讀取列表中的值 #!/bin/bash #basic for command for test in a b c d e f do echo The next state is $test done 每次for命令經過提供的值列表進行矢代時,它將列表中想下個值賦值給變量 [root@localhost ~]# ./test1.sh The next state is a The next state is b The next state is c The next state is d The next state is e The next state is f
2.讀取列表中的複雜值 #!/bin/bash for test in i don\'t know do echo "Word:$test" done 注意:分號(')這裏須要加斜槓(\)進行轉義 [root@localhost ~]# ./test2.sh Word:i Word:don't Word:know
3.從變量讀取列表 #!/bin/bash list="a b c d " for state in $list do echo "Have you ever visited $state?" done [root@localhost ~]# ./test4.sh Have you ever visited a? Have you ever visited b? Have you ever visited c? Have you ever visited d?
4.讀取命令中的值 生成列表中使用的另外一個方法是使用命令輸出,能夠使用反引號字符來執行生成輸出的任何命令,而後在for命令中使用命令輸出: 新建一個states文件,而且添加數據內容 [root@localhost ~]# cat states ak bn cd dr #!/bin/bash file="states" for state in `cat $file` do echo "Visit beautiful $state" done [root@localhost ~]# ./test5.sh Visit beautiful ak Visit beautiful bn Visit beautiful cd Visit beautiful dr
5.改變字段分隔符 內部字段分隔符(IFS),bash shell將如下字符看做是字段分隔符 空格 製表符 換行符 #!/bin/bash file="states" IFS=$'\n' for state in `cat $file` do echo "Visit beautiful $state" done IFS=$'\n'通知bash shell在數值中忽略空格和製表符
6.使用通配符讀取目錄 #!/bin/bash for file in /home/l* do if [ -d "$file" ] then echo "$file is a directory" elif [ -f "$file" ] then echo "$file is a file" fi done [root@localhost ~]# ./test6.sh /home/ley is a directory for命令失代/home/ley列表的結果,而後用test命令查看是目錄(-d)仍是文件(-f)