循环的中断

Bash 提供了两个内部命令breakcontinue,用来在循环内部跳出循环。
- break命令立即终止循环,程序继续执行循环块之后的语句,即不再执行剩下的循环。
- continue命令立即终止本轮循环,开始执行下一轮循环。

项目 bash csh
break #!/bin/bash
for number in 1 2 3 4 5 6 do
echo “number is $number”
if [ “$number” = “3” ]; then
break
fi
done
continue #!/bin/bash
while read -p “What file do you want to test?” filename do
if [ ! -e “$filename” ]; then
echo “The file does not exist.”
continue
fi
echo “You entered a valid file..”
done

while 循环的用法

while循环有一个判断条件,只要符合条件,就不断循环执行指定的语句。

项目 bash csh
while while expression; do
commands
done
while(expression)
commands
continue
break
end
示例 #关键字do可以跟while不在同一行,这时两者之间不需要使用分号分隔。
while true
do
echo ‘Hi, while looping …’;
done
#while循环写成一行,也是可以的
while true; do echo ‘Hi, while looping …’; done

until 循环的用法

until循环与while循环恰好相反,只要不符合判断条件(判断条件失败),就不断循环执行指定的语句。一旦符合判断条件,就退出循环。

项目 bash csh
while until condition; do
commands
done
示例 #!/bin/bash
number=0
until [ “$number” -ge 10 ]; do
echo “Number = $number”
number=$((number + 1))
done

for…in 循环

for...in循环用于遍历列表的每一项。

for循环会依次从list列表中取出一项,作为变量variable,然后在循环体中进行处理。

项目 bash csh
for…in for variable in list do
commands
done
示例 #!/bin/bash
for i in word1 word2 word3; do
echo $i
done
列表由通配符产生 for i in *.png; do
ls -l $i
done
列表通过子命令产生 #!/bin/bash
count=0
for i in $(cat ~/.bash_profile); do
count=$((count + 1))
echo “Word $count ($i) contains $(echo -n $i | wc -c) characters”
done

for

项目 bash csh
for for (( expression1; expression2; expression3 )); do
commands
done
示例 for (( i=0; i<5; i=i+1 )); do
echo $i
done
#直到用户输入了一个点(.)为止,才会跳出循环
for ((;;)) do
read var
if [ “$var” = “.” ]; then
break
fi
done

参考文献

  1. 阮一峰.Bash 脚本教程[EB/OL].https://wangdoc.com/bash, 2020/12/21.

    该教程的部分内容是比较完善的。

姊妹篇

  1. csh 、 bash 的基础语法对照:变量

  2. csh 、 bash 的基础语法对照:判断表达式

  3. csh 、 bash 的基础语法对照:循环表达式