循环语句| Shell脚本

Shell脚本中的循环语句: 总共有3条循环语句可用于bash编程

null
  1. while语句
  2. 声明
  3. 直到声明

要改变循环语句的流程,需要使用两个命令:,

  1. 打破
  2. 持续

它们的描述和语法如下:

  • while语句 这里对命令进行求值,并根据结果执行循环,如果命令提升为false,则循环将终止 语法
    while command
    do
       Statement to be executed
    done
  • 声明 for循环对项目列表进行操作。它为列表中的每个项目重复一组命令。 这里var是变量的名称,word1到wordN是由空格(单词)分隔的字符序列。每次执行for循环时,变量var的值都被设置为单词列表中的下一个单词word1到wordN。 语法
    for var in word1 word2 ...wordn
    do
       Statement to be executed
    done
  • 直到声明 直到循环执行的次数与条件/命令计算为false的次数相同。当条件/命令变为真时,循环终止。 语法
    
    until command
    do
       Statement to be executed until command is true
    done
    

示例程序

例1: 用break语句实现for循环

#Start of for loop
for a in 1 2 3 4 5 6 7 8 9 10
do
# if a is equal to 5 break the loop
if [ $a == 5 ]
then
break
fi
# Print the value
echo "Iteration no $a"
done


输出

$bash -f main.sh
Iteration no 1
Iteration no 2
Iteration no 3
Iteration no 4

例2: 用continue语句实现for循环

for a in 1 2 3 4 5 6 7 8 9 10
do
# if a = 5 then continue the loop and
# don't move to line 8
if [ $a == 5 ]
then
continue
fi
echo "Iteration no $a"
done


输出

$bash -f main.sh
Iteration no 1
Iteration no 2
Iteration no 3
Iteration no 4
Iteration no 6
Iteration no 7
Iteration no 8
Iteration no 9
Iteration no 10

例3: 实现while循环

a=0
# -lt is less than operator
#Iterate the loop until a less than 10
while [ $a -lt 10 ]
do
# Print the values
echo $a
# increment the value
a=`expr $a + 1`
done


输出:

$bash -f main.sh
0
1
2
3
4
5
6
7
8
9

例4: 实现直到循环

a=0
# -gt is greater than operator
#Iterate the loop until a is greater than 10
until [ $a -gt 10 ]
do
# Print the values
echo $a
# increment the value
a=`expr $a + 1`
done


输出:

$bash -f main.sh
0
1
2
3
4
5
6
7
8
9
10

注: Shell脚本是一种区分大小写的语言,这意味着在编写脚本时必须遵循正确的语法。

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享