shell (seven) cycle

main content

  • for loop
  • while loop
  • until loop
  • Out of the loop

for loop

The for loop format:

for 变量 in 列表
do
command1
command2
...
commandN
done

List is a sequence of a set of values (numeric, string, etc.), each of which values separated by a space. Each time through the loop, the next will be a value to the variable list.
inList is optional, if you do not use it, for the position loop parameters using the command line.

  • Example a
    sequential digital output in the current list:
      
      
1
2
3
4
      
      
for loop in 1 2 3 4 5
do
echo "The value is: $loop"
done
  • According to the second
    order of the output string of characters:
      
      
1
2
3
4
      
      
for str in 'This is a string'
do
echo $str
done
  • Example Three
    display main directory file beginning .bash:
      
      
1
2
3
4
5
      
      
#!/bin/bash
for FILE in $HOME/.bash*
do
echo $FILE
done

while loop

while loop continues to execute a series of commands, but also for reading data from the input file; Generally, this is a test condition, the condition is true cycle continues. The format is:

while command
do
  Statement(s) to be executed if command is true
done
  • Example a
    COUNTER count
      
      
1
2
3
4
5
6
      
      
COUNTER=0
while [ $COUNTER -lt 5 ]
do
COUNTER='expr $COUNTER+1'
echo $COUNTER
done
  • Example Two
    read keyboard information, press The end of the cycle.
      
      
1
2
3
4
5
6
      
      
echo 'type <CTRL-D> to terminate'
echo -n 'enter your most liked film: '
while read FILM
大专栏   shell (七) 循环ne">do
echo "Yeah! great film the $FILM"
done

until循环

until 循环执行一系列命令直至条件为 true 时停止。until 循环与 while 循环在处理方式上刚好相反。
command 一般为条件表达式,如果返回值为 false,则继续执行循环体内的语句,否则跳出循环。
until 循环格式为:

until command
do
  Statement(s) to be executed until command is true
done

  • 输出 0 ~ 9
      
      
1
2
3
4
5
6
      
      
a=0
until [ ! $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done

跳出循环

在循环过程中,有时候需要在未达到循环结束条件时强制跳出循环,Shell也使用 break 和 continue 来跳出循环。

break

break命令允许跳出本层所有循环(终止执行后面的所有循环)

break n 表示跳出第 n 层循环。

例如:

      
      
1
2
3
4
5
6
7
8
9
10
11
12
      
      
for var1 in 1 2 3
do
for var2 in 0 5
do
if [ $var1 -eq 2 -a $var2 -eq 0 ]
then
break 2
else
echo "$var1 $var2"
be
done
done

Above, break 2 represents directly out of the outer loop.

continue

continue command and break commands similar, with one difference, it does not jump out of circulation all, just out of the current cycle.
continue nIt represents the n-th layer bounce cycle.

Guess you like

Origin www.cnblogs.com/wangziqiang123/p/11711019.html