Shell Flow Control

Unlike languages such as Java and PHP, flow control in sh cannot be empty. For example (the following is PHP flow control syntax):

Example

<?php
if (isset($_GET["q"])) {
    search(q);
}
else {
    // Do nothing
}

In sh/bash you cannot write it like this. If the else branch has no statements to execute, don't write that else.


if else

if

if statement syntax:

if condition
then
    command1 
    command2
    ...
    commandN 
fi

Written in one line (applicable to terminal command prompt):

if [ $(ps -ef | grep -c "ssh") -gt 1 ]; then echo "true"; fi

The trailingfiisifspelled in reverse; you'll encounter similar ones later.

if else

if else syntax:

if condition
then
    command1 
    command2
    ...
    commandN
else
    command
fi

if else-if else

if else-if else syntax:

if condition1
then
    command1
elif condition2 
then 
    command2
else
    commandN
fi

In if else,[...]in comparison statements, greater than uses-gt, and less than uses-lt。

if [ "$a" -gt "$b" ]; then
    ...
fi

If using((...))as the comparison statement, greater than and less than can be used directly>and<。

if (( a > b )); then
    ...
fi

The following example checks whether two variables are equal:

Example

a=10
b=20
if [ $a == $b ]
then
   echo "a equals b"
elif [ $a -gt $b ]
then
   echo "a is greater than b"
elif [ $a -lt $b ]
then
   echo "a is less than b"
else
   echo "No matching condition"
fi

Output:

a 小于 b

Using((...))as the comparison statement:

Example

a=10
b=20
if (( $a == $b ))
then
   echo "a equals b"
elif (( $a > $b ))
then
   echo "a is greater than b"
elif (( $a < $b ))
then
   echo "a is less than b"
else
   echo "No matching condition"
fi

Output:

a 小于 b

The if else statement is often used together with the test command, as shown below:

Example

num1=$[2*3]
num2=$[1+5]
if test $[num1] -eq $[num2]
then
    echo 'The two numbers are equal!'
else
    echo 'The two numbers are not equal!'
fi

Output:

The two numbers are equal!

for loop

Similar to other programming languages, Shell supports for loops.

The general format of a 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 in the list. The commands can be any valid shell commands and statements. The in list can contain substitutions, strings, and filenames.

The in list is optional. If you don't use it, the for loop uses the positional parameters of the command line.

For example, output the numbers in the current list in order:

Example

for loop in 1 2 3 4 5
do
    echo "The value is: $loop"
done

Output:

The value is: 1
The value is: 2
The value is: 3
The value is: 4
The value is: 5

Output the characters in a string in order:

#!/bin/bash

for str in This is a string
do
    echo $str
done

Output:

This
is
a
string

while statement

The while loop is used to continuously execute a series of commands and also to read data from an input file. 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, the condition returns true. int starts from 1, and each time the loop processes, int increases by 1. Running the above script returns the numbers 1 to 5, then terminates.

Example

#!/bin/bash
int=1
while(( $int<=5 ))
do
    echo $int
    let "int++"
done

Run the script, output:

1
2
3
4
5

The above example uses the Bash let command, which is used to execute one or more expressions. In variable calculations, you do not need to add $ to represent variables. For details, see:Bash let command

。

The while loop can be used to read keyboard input. In the following example, the input is set to the variable FILM, and press <Ctrl-D> to end the loop.

Example

echo 'Press <CTRL-D> to exit'
echo -n 'Enter the name of your favorite website: '
while read FILM
do
    echo "Yes!$FILMis a good website"
done

Run the script, the output is similar to the following:

按下 <CTRL-D> 退出
输入你最喜欢的网站名:Example
是的!Example 是一个好网站

Infinite loop

Infinite loop syntax format:

while :
do
    command
done

Or

while true
do
    command
done

Or

for (( ; ; ))


until loop

The until loop executes a series of commands until the condition becomes true, then stops.

The until loop is exactly the opposite of the while loop in its handling method.

Generally, while loops are better than until loops, but at certain times—only in very rare cases—until loops are more useful.

until syntax format:

until condition
do
    command
done

condition is generally a conditional expression. If the return value is false, the statements inside the loop body continue to execute; otherwise, it breaks out of the loop.

In the following example, we use the until command to output the numbers 0 ~ 9:

Example

#!/bin/bash

a=0

until [ ! $a -lt 10 ]
do
   echo $a
   a=`expr $a + 1`
done

Run result:

The output result is:

0
1
2
3
4
5
6
7
8
9

case ... esac

case ... esacis a multi-choice statement, similar to the switch ... case statement in other languages. It is a multi-branch selection structure. Each case branch starts with a right parenthesis and ends with two semicolons;;means break, that is, the execution ends, and it jumps out of the entire case ... esac statement. esac (which is case spelled backwards) serves as the end marker.

You can use the case statement to match a value with a pattern. If the match succeeds, the corresponding command is executed.

case ... esacThe syntax format is as follows:

case 值 in
模式1)
    command1
    command2
    ...
    commandN
    ;;
模式2)
    command1
    command2
    ...
    commandN
    ;;
esac

The working method of case is as shown above. The value must be followed by the wordin, each pattern must end with a right parenthesis. The value can be a variable or a constant. After matching finds that the value conforms to a pattern, all commands in between begin execution until;;。

The value will check each pattern for a match. Once a pattern matches, after executing the corresponding commands of the matched pattern, it will not continue with other patterns. If no pattern matches, use the asterisk * to capture the value, and then execute the following commands.

The following script prompts for input from 1 to 4 and matches against each pattern:

Example

echo 'Enter a number between 1 and 4:'
echo 'The number you entered is:'
read aNum
case $aNum in
    1)  echo 'You chose 1'
    ;;
    2)  echo 'You chose 2'
    ;;
    3)  echo 'You chose 3'
    ;;
    4)  echo 'You chose 4'
    ;;
    *)  echo 'You did not enter a number between 1 and 4'
    ;;
esac

Entering different content will produce different results, for example:

输入 1 到 4 之间的数字:
你输入的数字为:
3
你选择了 3

The following script matches strings:

Example

#!/bin/sh

site="example"

case "$site" in
   "example") echo "Example Tutorial"
   ;;
   "google") echo "Google Search"
   ;;
   "taobao") echo "Taobao"
   ;;
esac

The output result is:

Example

Breaking Out of Loops

During a loop, sometimes you need to force break out of the loop before the loop end condition is reached. Shell uses two commands to implement this function:breakandcontinue。

break command

The break command allows you to break out of all loops (terminating the execution of all subsequent loops).

In the following example, the script enters an infinite loop until the user enters a number greater than 5. To break out of this loop and return to the shell prompt, you need to use the break command.

Example

#!/bin/bash
while :
do
    echo -n "Enter a number between 1 and 5:"
    read aNum
    case $aNum in
        1|2|3|4|5) echo "The number you entered is$aNum!"
        ;;
        *) echo "The number you entered is not between 1 and 5! Game over"
            break
        ;;
    esac
done

Execute the above code, the output is:

输入 1 到 5 之间的数字:3
你输入的数字为 3!
输入 1 到 5 之间的数字:7
你输入的数字不是 1 到 5 之间的! 游戏结束

continue

The continue command is similar to the break command, with only one difference: it does not break out of all loops, only the current loop.

Modify the above example:

Example

#!/bin/bash
while :
do
    echo -n "Enter a number between 1 and 5: "
    read aNum
    case $aNum in
        1|2|3|4|5) echo "The number you entered is$aNum!"
        ;;
        *) echo "The number you entered is not between 1 and 5!"
            continue
            echo "Game over"
        ;;
    esac
done

Running the code shows that when a number greater than 5 is entered, the loop in this example does not end. The statementecho "Game over"will never be executed.

Other extensions