English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
和 Java、PHP 等语言不一样,sh 的流程控制不可为空,如(以下为 PHP 流程控制写法):
<?php if (isset($_GET["q"])) { search(q); } else { // 不做任何事情 }
在 sh/bash 里可不能这么写,如果 else 分支没有语句执行,就不要写这个 else。
if 语句语法格式:
if condition then command1 command2 ... commandN fi
写成一行(适用于终端命令提示符):
if [ $(ps -ef | grep -c "ssh") -gt 1 ]; then echo "true"; fi
末尾的 fi 就是 if 倒过来拼写,后面还会遇到类似的。
if else 语法格式:
if condition then command1 command2 ... commandN else command fi
if else-if else 语法格式:
if condition1 then command1 elif condition2 then command2 else commandN fi
以下示例判断两个变量是否相等:
a=10 b=20 if [ $a == $b ] then echo "a 等于 b" elif [ $a -gt $b ] then echo "a 大于 b" elif [ $a -lt $b ] then echo "a 小于 b" else echo "没有符合的条件" fi
Output result:
a 小于 b
if else 语句经常与 test 命令结合使用,如下所示:
num1=$[2*3] num2=$[1+5] if test $[num1] -eq $[num2] then echo 'Two numbers are equal!' else echo 'Two numbers are not equal!' fi
Output result:
Two numbers are equal!
Similar to other programming languages, Shell supports for loops.
The general format of the for loop is:
for var in item1 item2 ... itemN do command1 command2 ... commandN done
Written in one line:
for var in item1 item2 ... itemN; do command1; command2... done;
When the variable value is in the list, the for loop executes all commands once, using the variable name to get the current value from the list. Commands can be any valid shell command and statement. The in list can contain substitutions, strings, and filenames.
The in list is optional, if it is not used, the for loop uses the command line position arguments.
For example, sequentially output the numbers in the current list:
for loop in 1 2 3 4 5 do echo "The value is: $loop" done
Output result:
The value is: 1 The value is: 2 The value is: 3 The value is: 4 The value is: 5
Sequentially output the characters in the string:
#!/bin/bash for str in This is a string do echo $str done
Output result:
This is a string
The while loop is used to continuously execute a series of commands and is also used to read data from input files. Its syntax format is:
while condition do command done
The following is a basic while loop, the test condition is: if int is less than or equal to 5, then the condition returns true. int starts from 1 Starting, each time the loop is processed, int is increased 1. Run the above script and return the number 1 hasta 5and then terminate.
#!/bin/bash int=1 while(( $int<=5 )) do echo $int let "int++" done
Run the script and output:
1 2 3 4 5
The above example uses the Bash let command, which is used to execute one or more expressions, variables do not need to be prefixed with $ for calculation, for more information, please refer to:Bash let command
.
The while loop can be used to read keyboard information. In the following example, the input information is set to the variable FILM, press <Ctrl-D> End loop.
echo 'Press <CTRL-D> Exit' echo -n 'Enter the name of your favorite website: ' while read FILM do echo "Yes! $FILM is a good website" done
Run the script and output something similar to the following:
Press <CTRL-D> Exit Enter the name of your favorite website: Base Tutorial Website Yes! Base Tutorial Website is a good website
Infinite loop syntax format:
while : do command done
或者
while true do command done
或者
for (( ; ; ))
until 循环执行一系列命令直至条件为 true 时停止。
until 循环与 while 循环在处理方式上刚好相反。
一般 while 循环优于 until 循环,但在某些时候—也只是极少数情况下,until 循环更加有用。
until 语法格式:
until condition do command done
condition 一般为条件表达式,如果返回值为 false,则继续执行循环体内的语句,否则跳出循环。
以下示例我们使用 until 命令来输出 0 ~ 9 的数字:
#!/bin/bash a=0 until [ ! $a -lt 10 ] do echo $a a=`expr $a + 1` done
运行结果:
el resultado de salida es:
0 1 2 3 4 5 6 7 8 9
case ... esac 为多选择语句,与其他语言中的 switch ... case 语句类似,是一种多分枝选择结构,每个 case 分支用右圆括号开始,用两个分号 ;; 表示 break,即执行结束,跳出整个 case ... esac 语句,esac(就是 case 反过来)作为结束标记。
可以用 case 语句匹配一个值与一个模式,如果匹配成功,执行相匹配的命令。
case ... esac 语法格式如下:
case 值 in 模式1) command1 command2 ... commandN ;; 模式2) command1 command2 ... commandN ;; esac
case 工作方式如上所示,取值后面必须为单词 in,每一模式必须以右括号结束。取值可以为变量或常数,匹配发现取值符合某一模式后,其间所有命令开始执行直至 ;;。
取值将检测匹配的每一个模式。一旦模式匹配,则执行完匹配模式相应命令后不再继续其他模式。如果无一匹配模式,使用星号 * 捕获该值,再执行后面的命令。
下面的脚本提示输入 1 hasta 4,与每一种模式进行匹配:
echo '输入' 1 hasta 4 之间的数字:' echo '你输入的数字为:' read aNum case $aNum in 1) echo '你选择了' 1' ;; 2) echo '你选择了' 2' ;; 3) echo '你选择了' 3' ;; 4) echo '你选择了' 4' ;; *) echo '你没有输入' 1 hasta 4 之间的数字' ;; esac
输入不同的内容,会有不同的结果,例如:
ingresar 1 hasta 4 número entre los " 你输入的数字为: 3 你选择了 3
下面的脚本匹配字符串:
#!/bin/sh site=\3codebox\" case \ "w3codebox") echo "基础教程网" ;; "google") echo "Google 搜索" ;; "taobao") echo "淘宝网" ;; esac
el resultado de salida es:
web tutorial básico
En el proceso del bucle, a veces es necesario salir forzadamente del bucle antes de alcanzar la condición de finalización del bucle. Shell utiliza dos comandos para implementar esta función: break y continue.
El comando break permite salir de todos los bucles (detener la ejecución de todos los bucles posteriores).
En el siguiente ejemplo, el script entra en un bucle infinito hasta que el usuario ingrese un número mayor que5. Para salir de este bucle y volver al símbolo del prompt de shell, es necesario usar el comando break.
#!/bin/bash while : do echo -ingresar 1 hasta 5 número entre los " read aNum case $aNum in 1|2|3|4|5) echo "El número que ingresaste es $aNum!" ;; *) echo "El número que ingresaste no es" 1 hasta 5 entre los "! Juego final" break ;; esac done
Ejecutar el código anterior y el resultado de salida es:
ingresar 1 hasta 5 número entre los "3 El número que ingresaste es 3! ingresar 1 hasta 5 número entre los "7 El número que ingresaste no es 1 hasta 5 entre los "! Juego final
El comando continue es similar al comando break, pero con una diferencia, no salta de todos los bucles, solo sale del bucle actual.
Modificar el ejemplo anterior:
#!/bin/bash while : do echo -ingresar 1 hasta 5 número entre los " read aNum case $aNum in 1|2|3|4|5) echo "El número que ingresaste es $aNum!" ;; *) echo "El número que ingresaste no es" 1 hasta 5 entre los "! continue echo "Final del juego" ;; esac done
Ejecutar el código y descubrir que cuando se introduce un número mayor que5siempre que se introduzca el númeroecho "Final del juego"Nunca se ejecutará.