Shell编程-While循环

时间:2020-02-23 14:45:09  来源:igfitidea点击:

在本教程中,我们将学习Shell编程中的While循环。

while循环类似于for循环,只要满足某些给定条件,就可以帮助多次执行代码块。

while语法

while [ condition ]
do
  # body of while loop
done

条件是某些条件,如果满足则将导致循环主体的执行。

要退出while循环,我们使条件失败。

要退出脚本,我们可以使用exit命令。

例1:编写一个Shell脚本以使用while循环从1到5打印

#!/bin/sh

# initialise i
i=1

while [ $i -le 5 ]
do
  # echo i
  echo $i

  # update i
  i=`expr $i + 1`
done
$sh example01.sh 
1
2
3
4
5

通过编写以下代码,我们可以实现相同的结果。

#!/bin/sh

# initialise i
i=1

while [ $i -le 5 ]
do
  # echo i
  echo $i

  # update i
  i=$(( $i + 1 ))
done

嵌套while循环

我们可以通过将while循环放置在另一个while循环的主体中来嵌套while循环。

while [ condition_outer ]
do

  # body of the outer while loop

  while [ condition_inner ]
  do
    # body of the inner while loop
  done

done

例2:编写Shell脚本以打印以下模式

1
1 3
1 3 5
1 3 5 7

为此,我们将使用r变量来计数行,使用c变量来计数列。
我们将使用counter变量来打印数字。

#!/bin/sh

# for the rows
r=1

while [ $r -le 4 ]
do

  # for the output
  count=1
  
  # for the column
  c=1

  while [ $c -le $r ]
  do
  	# print the value
  	printf "$count "

    # update count
    count=$(( $count + 2 ))

    # update c
    c=$(( $c + 1 ))
  done

  # go to new line
  printf "\n"

  # update r
  r=$(( $r + 1 ))
  
done
$sh example02.sh 
1 
1 3 
1 3 5 
1 3 5 7