Easy Tutorial
❮ Linux Comm Stat Linux Comm Mtoolstest ❯

Shell Flow Control

Unlike languages such as Java and PHP, sh flow control cannot be empty. For example, the following is a PHP flow control writing style:

Example

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

In sh/bash, you cannot write it this way. If there are no statements to execute in the else branch, do not write the else.


if else

fi

The syntax for the if statement is:

if condition
then
    command1 
    command2
    ...
    commandN 
fi

Written in one line (suitable for terminal command prompt):

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

The fi at the end is if spelled backwards, and you will encounter similar constructs later.

if else

The syntax for the if else statement is:

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

if else-if else

The syntax for the if else-if else statement is:

if condition1
then
    command1
elif condition2 
then 
    command2
else
    commandN
fi

In the [...] condition statement for if else, greater than is represented by -gt and less than by -lt.

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

If using ((...)) as the condition statement, greater than and less than can be directly represented by > and <.

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

The following example checks if two variables are equal:

Example

a=10
b=20
if [ $a == $b ]
then
   echo "a is equal to 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 conditions"
fi

Output:

a is less than b

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

Example

a=10
b=20
if (( $a == $b ))
then
   echo "a is equal to 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 conditions"
fi

Output:

a is less than b

if else statements are often used in conjunction 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 for 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 values are in the list, the for loop executes all commands, using the variable name to get the current value in the list. Commands can be any valid shell commands and statements. The in list can include substitutions, strings, and filenames.

The in list is optional. If not used, the for loop uses the positional parameters from the command line.

For example, sequentially outputting numbers in the current list:

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

Sequentially outputting characters in a string:

#!/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 it is also used to read data from an input file. Its syntax is:

while condition
do
    command

Below is a basic while loop where the test condition is: if the integer is less than or equal to 5, then the condition returns true. The integer starts at 1, and with each loop iteration, the integer is incremented by 1. Running the script will output numbers 1 through 5 and then terminate.

Example

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

Running the script outputs:

1
2
3
4
5

The above example uses the Bash let command, which is used to execute one or more expressions. Variables in calculations do not need to be prefixed with $; for more details, see Bash let Command.

While loops can also be used to read keyboard input. In the following example, input is assigned to the variable FILM, and the loop ends when <Ctrl-D> is pressed.

Example

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

Running the script outputs something like:

Press <CTRL-D> to exit
Enter your favorite website name: tutorialpro.org
Yes! tutorialpro.org is a great website

Infinite Loop

Infinite loop syntax:

while :
do
    command
done

or

while true
do
    command
done

or

for (( ; ; ))

until Loop

The until loop executes a series of commands until a condition becomes true.

The until loop is opposite to the while loop in terms of handling conditions.

While loops are generally preferred over until loops, but in some cases, the until loop can be more useful.

until syntax:

until condition
do
    command
done

The condition is typically a conditional expression. If it returns false, the commands inside the loop are executed; otherwise, the loop is exited.

The following example uses the until command to output numbers 0 through 9:

Example

#!/bin/bash

a=0

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

Running the script outputs:

0
1
2
3
4
5
6
7
8
9

case ... esac

case ... esac is a multi-choice statement, similar to the switch ... case statement in other languages. It is a multi-branch selection structure where each case branch starts with a right parenthesis and ends with two semicolons ;;, indicating a break, i.e., the end of execution, and exit from the entire case ... esac statement. esac (case spelled backward) marks the end.

The case statement can match a value to a pattern. If a match is successful, the corresponding commands are executed.

case ... esac syntax:

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

The value must be followed by the word in, and each pattern must end with a right parenthesis. The value can be a variable or a constant. Once a pattern match is found, all corresponding commands are executed until ;;.

The value is tested against each pattern. Once a pattern matches, the corresponding commands are executed, and no further patterns are checked. If no pattern matches, the asterisk * captures the value and executes the subsequent commands.

The following script prompts for a number between 1 and 4 and matches it against each pattern:

Example

echo 'Enter a number between 1 and 4:'
echo 'You entered:'
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 values results in different outputs, for example:

Enter a number between 1 and 4:
You entered:
3
You chose 3

The following script matches strings:

Example

#!/bin/sh

site="tutorialpro"

case "$site" in
   "tutorialpro") echo "tutorialpro.org" 
   ;;
   "google") echo "Google Search" 
   ;;
   "taobao") echo "Taobao" 
   ;;
esac

Output result:

tutorialpro.org

Breaking Out of Loops

During loop execution, sometimes it is necessary to forcefully break out of the loop before reaching its termination condition. Shell uses two commands to achieve this functionality: break and continue.

break Command

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

In the example below, the script enters an infinite loop until the user inputs a number greater than 5. To break out of this loop and return to the shell prompt, the break command is used.

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 "You entered the number $aNum!"
        ;;
        *) echo "The number you entered is not between 1 and 5! Game over"
            break
        ;;
    esac
done

Executing the above code, the output is:

Enter a number between 1 and 5: 3
You entered the number 3!
Enter a number between 1 and 5: 7
The number you entered is not between 1 and 5! Game over

continue

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

Modifying the previous 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 "You entered the number $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 does not end, and the statement echo "Game over" is never executed.

❮ Linux Comm Stat Linux Comm Mtoolstest ❯