for in 格式 for 無$變量 in 字符串 do $變量 done
| 一簡單的字符串 枚舉遍歷法,利用for in格式對(duì)字符串按空格切份的功能
SERVICES="80 22 25 110 8000 23 20 21 3306 "
for x in $SERVICES do iptables -A INPUT -p tcp --dport $x -m state --state NEW -j ACCEPT done
| for variable in values --------字符串?dāng)?shù)組依次賦值 #!/bin/sh for i in a b c 字符串列表A B C 字符串用空格分隔,沒有括號(hào),沒有逗號(hào), 然后循環(huán)將其依次賦給變量i 變量沒有$ do echo "i is $i" done | [macg@machome ~]$ sh test.sh i is a i is b i is c
|
for in 里,變量和*不等價(jià) #!/bin/bash
for i in *.h ; do cat ${i}.h done
| [macg@vm test]$ ./tip.sh cat: *.h.h: No such file or directory $i代表的是整個(gè)路徑,而不是*.h里的.h前面的部分
| 改正 #!/bin/bash
for i in *.h do cat $i done
| [macg@vm test]$ echo hahaha >>1.h [macg@vm test]$ echo ha >>2.h
[macg@vm test]$ ./tip.sh hahaha ha
| 例2: for i in /etc/profile.d/*.sh do $i done
| $i代表的是/etc/profile.d/color.sh, /etc/profile.d/alias.sh, /etc/profile.d/default.sh | for in 對(duì)(命令行,函數(shù))參數(shù)遍歷 test() { local i
for i in $* ; do echo "i is $i" done } $*是字符串:以"參數(shù)1 參數(shù)2 ... " 形式保存所有參數(shù) $i是變量i的應(yīng)用表示
| [macg@machome ~]$ sh test.sh p1 p2 p3 p4
i is p1 i is p2 i is p3 i is p4
|
for in語句與通配符*合用,批量處理文件 批量改文件名 [root@vm testtip]# ls aaa.txt ccc.txt eee.txt ggg.txt hhh.txt jjj.txt lll.txt nnn.txt bbb.txt ddd.txt fff.txt go.sh iii.txt kkk.txt mmm.txt ooo.txt
| [root@vm testtip]# cat go.sh for i in *.txt *.txt相當(dāng)于一個(gè)字符串?dāng)?shù)組,依次循環(huán)賦值給i do mv "$i" "$i.bak" done
| [root@vm testtip]# sh go.sh
[root@vm testtip]# ls aaa.txt.bak ccc.txt.bak eee.txt.bak ggg.txt.bak hhh.txt.bak jjj.txt.bak lll.txt.bak nnn.txt.bak bbb.txt.bak ddd.txt.bak fff.txt.bak go.sh iii.txt.bak kkk.txt.bak mmm.txt.bak ooo.txt.bak
| for in語句與` `和$( )合用,利用` `或$( )的將多行合為一行的缺陷,實(shí)際是合為一個(gè)字符串?dāng)?shù)組 for i in $(ls *.txt) do echo $i done
| [macg@machome ~]$ sh test 111-tmp.txt 111.txt 22.txt 33.txt
| 或者說,利用for in克服` `和$( ) 的多行合為一行的缺陷
利用for in 自動(dòng)對(duì)字符串按空格遍歷的特性,對(duì)多個(gè)目錄遍歷 LIST="rootfs usr data data2" for d in $LIST; do mount /backup/$d rsync -ax --exclude fstab --delete /$d/ /backup/$d/ umount /backup/$d done
|
|