如果需要重复执行一组语句,那么我们需要使用循环语句。以下是shell脚本支持的语句列表。
6.1。 While循环
6.2。直到循环
6.3。对于循环
6.4。选择循环
6.1。 While循环
While循环是一个循环语句,用于执行一组语句,直到条件为真为止。一旦条件变为假,它将退出循环。下面是while循环的语法。
句法:
而 [ 健康)状况 ] do #statements done
注意:
在这里我们用“while”, “do” and “done” keywords used in 而 loop.
例:
#!/bin/bash var=5 while [ $var -ge 1 ] do echo "the number is $var" var=$(($var - 1)) done
输出:
the number is 5 the number is 4 the number is 3 the number is 2 the number is 1
6.2。直到循环
直到循环类似于扭曲的循环。在这里,循环将继续执行,直到表达式变为真为止。只要条件失败,循环就会继续。
句法:
直到 [ 健康)状况 ] do #statements done
注意:这里我们使用“until”, “do” and “done” keywords used in 直到 loop.
例:
#!/bin/bash var=1 until [ $var -eq 5 ] do echo "the number is $var" var=$(( $var + 1 )) done
输出:
the number is 1 the number is 2 the number is 3 the number is 4
如您在上面的输出中看到的,“var”值变为5,将退出循环。因此它将不会打印数字5。
6.3。对于循环
For循环类似于while和直到循环,但是循环的次数应事先知道。有2种for循环。
1. The bash 对于m of 对于 loop:
句法:
对于 <variable_name> in <list> do #statements done
注意:
这里“for”, “in”, “do”, “done” are the keyword.
清单可以是数字列表,数组列表或任何其他具有项目列表的列表。
<variable_name> holds the 清单 of items, 上 e element at a time.
例:
#!/bin/bash for 变种 in 2 4 6 8 10 do echo "The 变种iable is $var" done
输出:
The 变种iable is 2 The 变种iable is 4 The 变种iable is 6 The 变种iable is 8 The 变种iable is 10
2。“c” style of 对于 loop:
对于 (( <initialization> ; <condition>; <递增或递减> )) do #statements done
这里“for”, “;”, “do”, “done”是使用的关键字。
<initialization> is used to initialize the 变种iable
<condition> 这里健康)状况 to be checked should be written. The statements between “do” and “done” will be executed 直到 the 健康)状况 become false.
<递增或递减>在每个循环之后,将执行此表达式。
例:
#!/bin/bash for (( 变种=0 ; 变种<=5; 变种++ )) do echo "The 变种iable is $var" done
输出:
The 变种iable is 0 The 变种iable is 1 The 变种iable is 2 The 变种iable is 3 The 变种iable is 4 The 变种iable is 5
6.4。选择循环
当我们想向用户显示选项时,通常使用select循环。通常,select循环将与case或else-if语句一起使用,以实现更好的控制。从下面的语法中可以看到,没有办法退出select循环,break语句用于退出select循环。
句法:
选择 <variable_name> in <list> do #statements done
注意:
“select” “in” “do” “done”是使用的关键字。
中的元素“list”将作为菜单显示给用户。
例:
#!/bin/bash echo "Select an operating system from below" select 变种 in linux unix macOS windows do echo "The OS you have 选择ed is $var" done
输出:
Select an operating system from below 1) linux 2) unix 3) macOS 4) windows #? 3 The OS you have 选择ed is macOS
该网站上可用的教程列表:
C编程20+章 | C ++编程80+章 |
100多个编码问题 | 数据结构和算法85+章 |
系统设计20+章 | Shell脚本编写12章 |
4g LTE 60+章节 | 最常见的编码问题 |
5G NR 50+章 | Linux系统编程20+章 |