與其他編程語言類似,Shell支持for循環。
for循環一般格式為:
for 變量 in 列表 do command1 command2 ... commandN done
列表是一組值(數字、字符串等)組成的序列,每個值通過空格分隔。每循環一次,就將列表中的下一個值賦給變量。
in 列表是可選的,如果不用它,for 循環使用命令行的位置參數。
例如,順序輸出當前列表中的數字:
- for loop in 1 2 3 4 5
- do
- echo "The value is: $loop"
- done
運行結果:
The value is: 1 The value is: 2 The value is: 3 The value is: 4 The value is: 5
順序輸出字符串中的字符:
- for str in 'This is a string'
- do
- echo $str
- done
運行結果:
This is a string
顯示主目錄下以 .bash 開頭的文件:
- #!/bin/bash
- for FILE in $HOME/.bash*
- do
- echo $FILE
- done
運行結果:
/root/.bash_history /root/.bash_logout /root/.bash_profile /root/.bashrc