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
變數沒有$
doecho "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 ;
docat$.h
done
[macg@vm test]$ ./tip.sh
cat:*.h.h: no such file or directory
$i代表的是整個路徑,而不是*.h裡的.h前面的部分
改正
#!/bin/bash
for i in *.h
docat$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()
$*是字串:以"引數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
domv "$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)
doecho $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
ceph儲存 linux下多路徑(multi-path)介紹及使用
指令碼樂園 shell程式設計迴圈結構
Shell 指令碼程式設計
1 執行shell的方法 指定shell bin sh 由sh執行指令碼 指令碼總是由sh解釋 顯示呼叫shell sh scriptname 在當前shell中執行指令碼 profile profile是可執行的 ksh profile profile是不可執行的 改變當前的執行環境責應輸入.pr...
Shell 指令碼程式設計
a file 如果 file 存在則為真。b file 如果 file 存在且是乙個塊特殊檔案則為真。c file 如果 file 存在且是乙個字特殊檔案則為真。d file 如果 file 存在且是乙個目錄則為真。e file 如果 file 存在則為真。f file 如果 file 存在且是乙個...
shell指令碼程式設計
今天看看shell程式設計,記錄下期中與想象中不一樣的地方 0.注釋用 1.shell的變數賦值 your name zhm 在your name和等號中間不能有空格,這和別的語言很不一樣,那麼在使用變數時和別的語言也不一樣,要使用 your name,一般要用 一定是大括號 2.那麼如何把乙個變數...