shell ——for in 迴圈 2013-03-28 18:06:29 標籤: for 迴圈
shell 編程——for in 迴圈 -------for in 格式-------
for 無$變數 in 字串 do $變數 done 一簡單的字串 枚舉遍曆法,利用for in格式對字串按空格切份的功能
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--------------字串數組依次賦值
#!/bin/sh for i in a b c 字串列表A B C 字串用空格分隔,沒有括弧,沒有逗號, 然後迴圈將其依次賦給變數i 變數沒有$ do echo "i is $i" done [macg@machome ~]$ sh test.sh i is a i is b i is c -------for in 裡,變數和*不等價-------
#!/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代表的是整個路徑,而不是*.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 對(命令列,函數)參數遍曆-------
test() { local i for i in $* ; do echo "i is $i" done } $*是字串:以"參數1 參數2 ... " 形式儲存所有參數 $i是變數i的應用表示 [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相當於一個字串數組,依次迴圈賦值給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語句與` `和$( )合用,利用` `或$( )的將多行合為一行的缺陷,實際是合為一個字串數組-------
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 自動對字串按空格遍曆的特性,對多個目錄遍曆-------
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 ********Linux Shell for迴圈寫法總結********
for((i=1;i<=10;i++));do echo $(expr $i \* 4);done