Shell编程之循环语句
for
Shell中的for循环有两种格式1
2
3
4
5
6
7
8
9# 格式一
for i list; do
commands
done
# 格式二
for (( i=0; i<10; i++ )) {
commands
}
示例1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 遍历序列
{1..5}/{a..z}/{A..Z} 生成序列
for i in {a..c}; do
echo "$i"
done
遍历参数
"#@" 与 "$*" 效果一致,但是使用 "$*"时一定注意加上双引号
for i in "$@"; do
echo "$i"
done
declare -a arr=(a b c)
遍历数组
"${arr[@]}" 获取数组所有元素
for i in "${arr[@]}"; do
echo "$i"
done
遍历数组
"${#arr[@]}" 获取数组元素个数
for((i=0; i<"${#arr[@]}"; i++)) {
echo "${arr[i]}"
}
while
若条件不为真,则退出循环1
2
3while condition; do
commands
done
示例1
2
3
4
5
6declare -i i=0
while [ $i -lt 3 ]; do
echo $i
let i++
done
until
若条件为真,则退出循环1
2
3until condition; do
commands
done
示例1
2
3
4
5
6declare -i i=0
until [ $i -eq 3 ]; do
echo $i
let i++
done