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