Conditional control and loop statement of shell script

Time:2021-7-21

Conditional judgment: if statement

Syntax format:


if [ expression ]
then
Statement(s) to be executed if expression is true
fi

Note: there must be a space between expression and bracket ([]), otherwise there will be a syntax error.

The if statement determines which branch to execute by judging whether the expression is true or false through relational operators. Shell has three if… Else statements:

If... Fi statement
If... Else... Fi statement
if ... elIf... Else... Fi statement

Example:


#!/bin/bash/
a=10
b=20
if [ $a == $b ]
then 
echo "a is equal to b"
elif [ $a -gt $b ]
then
echo "a is greater to b"
else
echo "a is less to b"
fi

The if… Else statement can also be written as a line and run as a command


a=10;b=20;if [ $a == $b ];then echo "a is equal to b";else echo "a is not equal to b";fi;

The if… Else statement is often used in combination with the test command


#!/bin/bash/
a=10
b=20
if test $a == $b 
then 
echo "a is equal to b"
else
echo "a is not equal to b"
fi

Branch control: case statement

Case… ESAC is a multi branch selection structure similar to switch… Case in other languages.

Example:


#!/bin/bash/
grade="B"
case $grade in 
"A") echo "Very Good!";;
"B") echo "Good!";;
"C") echo "Come On!";;
*) 
echo "You Must Try!"
echo "Sorry!";;
esac

The conversion to C language is as follows:


#include <stdio.h>
int main(){
char grade = 'B';
switch(grade){
case 'A': printf("Very Good!");break;
case 'B': printf("Very Good!");break;
case 'C': printf("Very Good!");break;
default: 
printf("You Must Try!");
printf("Sorry!");
break;
}
return 0;
}

It’s easy to understand by comparison. It’s very similar, but the format is different.

It should be noted that:

The first mock exam must be in, and each mode must end with the right bracket. The value can be a variable or a constant. After matching, the first mock exam is executed until all values are in accordance with a certain mode. Similar to break in other languages, it means to jump to the end of the whole case statement.

The value will detect each matching pattern. Once the pattern is matched, no other pattern will continue after the corresponding command of matching pattern is executed. If there is no matching pattern, use the asterisk * to capture the value, and then execute the following command.

Another example:


#!/bin/bash
option=""
case ${option} in
"-f") FILE=""
echo "File name is $FILE"
;;
"-d") DIR=""
echo "Dir name is $DIR"
;;
*) 
echo "`basename 

#!/bin/bash
option="${1}"
case ${option} in
"-f") FILE="${2}"
echo "File name is $FILE"
;;
"-d") DIR="${2}"
echo "Dir name is $DIR"
;;
*) 
echo "`basename ${0}`:usage: [-f file] | [-d directory]"
exit 1 # Command to come out of the program with status 1
;;
esac
`:usage: [-f file] | [-d directory]" exit 1 # Command to come out of the program with status 1 ;; esac

Results of operation:


$./test.sh
test.sh: usage: [ -f filename ] | [ -d directory ]
./test.sh -f index.html
File name is index.html

The special variable ${1} is used here to get the first parameter of the command line.

For loop

Shell’s for loop is different from C, PHP and other languages, and is very similar to python. Here is the syntax format:

For variable in list


do
command1
command2
...
commandN
done

Example:


#!/bin/bash/
for value in 1 2 3 4 5
do 
echo "The value is $value"
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 the string in order:


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

Results of operation:

This is a string

Traverse the files in the directory:


#!/bin/bash
for FILE in *
do
echo $FILE
done

The above code will traverse all the files in the current directory. Under Linux, you can try to change to another directory.

Traverse file content:

city.txt


beijing
tianjin
shanghai
#!/bin/bash
citys=`cat city.txt`
for city in $citys
echo $city
done

Output:

beijing
tianjin
shanghai

while Loop

As long as the conditions after while are satisfied, the code blocks in do are executed all the time.

The format is as follows:

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

After the command is executed, the control returns to the top of the loop, starting from the beginning until the test condition is false.

Example:


#!/bin/bash
c=0;
while [ $c -lt 3 ]
do
echo "Value c is $c"
c=`expr $c + 1`
done

Output:

Value c is 0
Value c is 1
Value c is 2

Here, because the shell itself does not support arithmetic operations, so the expr command is used for auto increment.

Until loop

The until loop executes a series of commands until the condition is true. The until loop is the opposite of the while loop. Generally, while loop is better than until loop, but in some cases, until loop is more useful.

The same effect can be achieved by changing the above example of while loop


#!/bin/bash
c=0;
until [ $c -eq 3 ]
do
echo "Value c is $c"
c=`expr $c + 1`
done

First, the statement block in do is running until the condition of until is satisfied.

Output:

Value c is 0
Value c is 1
Value c is 2

Jump out of the loop

In the process of loop, sometimes it is necessary to force the loop to jump out before the loop end condition is reached. Like most programming languages, shell also uses break and continue to jump out of the loop.

break

The break command allows you to jump out of all loops (terminate execution of all subsequent loops).


#!/bin/bash
i=0
while [ $i -lt 5 ]
do
i=`expr $i + 1`
if [ $i == 3 ]
then
break
fi
echo -e $i
done

Results of operation:

1
2

In nested loops, the break command can also be followed by an integer to indicate which level of loop to jump out of. For example:

break n

Indicates to jump out of the n-th layer loop.

continue

The continue command is similar to the break command, except that it does not jump out of all loops, just out of the current loop.


#!/bin/bash
i=0
while [ $i -lt 5 ]
do
i=`expr $i + 1`
if [ $i == 3 ]
then
continue
fi
echo -e $i
done

Results of operation:

1
2
4
5

The above content is a small series to introduce the shell script condition control and loop statements related knowledge, I hope to help you!