Conditional test, if and case conditional test statements of shell script

Posted by alsal on Mon, 07 Feb 2022 07:57:49 +0100

catalogue

1, Condition test

1.1.test command

1.2. File test

1.3. Integer value comparison

1.4. string comparison

1.5. Logic test

2, if statement

2.1. Single branch structure

2.2. Double branch structure

2.3. Multi branch structure

2.4. Nested if statement

3, case statement

4, Summary

1, Condition test

1.1.test command

Test whether a specific expression is true. When the condition is true, the return value of the test statement is 0, otherwise it is other values.

Format:
test Conditional expression
 or
[ Conditional expression ]  (Space is required on both sides of the conditional expression, and this method is more commonly used)

1.2. File test

File testing refers to judging whether the corresponding file or directory is based on the given path name, or whether the file is readable, writable, executable, etc.

Common options for file testing:

After the conditional test operation is executed, through the predefined variable "$?" The return status value of the test command can be obtained to judge whether the condition is true. For example, do the following to test whether the directory / media / exists, if the return value is "$?" If it is 0, it indicates that this directory exists. Otherwise, it indicates that it does not exist or exists but is not a directory.

[root@localhost ~]# test  -d /media/;echo $?
0      ### The return value is 0

Case:

[root@localhost ~]# test  -d /etc/;echo $?  ### Test whether it is a directory
0      ### The return value 0 # is the directory

[root@localhost ~]# test  -e /etc/abc;echo $?       ### Test whether the directory or file exists
1      ### Return value 1: the directory or file does not exist

[root@localhost ~]# test -f /etc/yum.conf ;echo $?      ### Test whether it is a file
0      ### The return value 0} is a file

[root@localhost ~]# test -r /etc/yum.conf ;echo $?      ### Test whether the current user has permission to read
0      ### Return value 0. Current user has read permission

[root@localhost ~]# test -w /etc/yum.conf ;echo $?      ### Test whether the current user has permission to write
0      ### Return value 0 # current user has writable permission

[root@localhost ~]# test -x /etc/yum.conf ;echo $?      ### Test whether the current user has permission to execute
1      ### Return value 1: the current user does not have execution permission

You can use "& &" and "echo" together

[root@localhost ~]# test  -d /etc/ && echo "yes"
yes

1.3. Integer value comparison

Integer value comparison refers to judging the relationship between the first number and the second number according to the given two integer values, such as whether it is greater than, equal to or less than the second number.

Format:
[ Integer 1 operator integer 2 ]

Common test operators

#Query whether the number of files in the current directory is greater than 10. If it is greater than 10, you will be prompted
[root@localhost ~]# ls | wc -l
11
[root@localhost ~]# Test ` LS | WC - L ` - GT 10 & & echo "the number of files is greater than 10"
The number of files is greater than 10
# Check whether the system memory is lower than 1300M. If it is lower than 1300M, you will be prompted
[root@localhost ~]#  free -m
              total        used        free      shared  buff/cache   available
Mem:           3771         724        1244          17        1801        2712
Swap:          2999           0        2999
[root@localhost ~]# free -m | grep "Mem" 
Mem:           3771         724        1244          17        1801        2712
[root@localhost ~]# free -m | grep "Mem" | awk '{print $4}'
1244
[root@localhost ~]# free=`free -m | grep "Mem" | awk '{print $4}'`
[root@localhost ~]# echo $free
1244
[root@localhost ~]# Test ` echo $free ` - LT 1300 & & echo "less than 1300M memory"
Insufficient memory 1300 M

1.4. string comparison

String comparison is usually used to check whether the user input and system environment meet the conditions. In the shell script that provides interactive operation, it can also be used to judge whether the location parameters entered by the user meet the requirements.

Format:
[string 1 = string 2] #### judge whether it is equal
[string 1! = string 2] #### judge whether it is unequal
[- z string] #### judge whether the string content is empty

Common test operators

# Judge whether the current system locale is "us.en". If not, prompt
[root@localhost ~]# echo $LANG
zh_CN.UTF-8
[root@localhost ~]# Test ` echo $LANG ` = "us.en" & & echo the current language is not us EN, the current language is ` echo $LANG` 
The current language is not us.en,The current language is zh_CN.UTF-8

1.5. Logic test

Logical testing refers to judging the dependency between two or more conditions. When the system task depends on several different conditions, a test process is required according to whether these conditions are established at the same time or as long as one of them is established.

Format:
[ Expression 1 ] Operator [ Expression 2 ]

Command 1 operator command 2

Common test operators

[root@localhost ~]# [ -d /etc ] && [ -r /etc ] && echo "you can open it "
you can open it 
[root@localhost ~]# [ -d /etc ] || [ -d /home  ] && echo " ok "
 ok 

2, if statement

2.1. Single branch structure

Format:
if [ Conditional judgment ]; than
	When the condition judgment is true, execute one or more commands
fi 					

Example 1:

# Use the single branch if statement to determine whether the test file exists
[root@localhost ~]# if test -e /etc ; then echo directory exists; fi
 Directory exists

[root@localhost ~]# if test -e /etc/yum.conf ; then echo file exists; fi
 File exists

Example 2:

Determine the mount point. If it does not exist, it will be created automatically

#!/bin/bash
MOUNT_DIR="/media/cdrom/ "
if [ ! -d $MOUNT_DIR ];
then
mkdir -p $MOUNT_DIF
fi

Example 3:

Judge whether the end of input is sh

#!/bin/bash
read -p "Please enter a file name:" file
if [[$file == *.sh ]] ;then
echo "This is a shell script"
fi

2.2. Double branch structure

The double branch if statement only performs another operation on the basis of a single branch when the "condition is not tenable", rather than "sitting idly by" without performing any operation.

if [ Conditional judgment ]; then
	When the condition judgment is true, one or more commands can be executed
else	
	When the condition judgment is not tenable, one or more commands can be executed
fi 		

In the judgment of the same data, if the data needs two different judgments, we need a double branch if statement:

Example 1:

Judge whether the current login user is an administrator

[root@localhost ~]# vim a.sh

#!/bin/bash
if [ $UID -eq 0 ];then
echo "The current login user is an administrator root"
else
echo "The current login user is not an administrator"
fi

[root@localhost ~]# sh a.sh
 The current login user is an administrator root

Example 2:

Check if the directory exists

[root@localhost ~]# vim b.sh

#!/bin/bash 
read -p "Check whether the directory exists. Please enter the directory:" aaa
if ls $aaa &> /dev/null
then
echo "Directory exists"
else
echo "Please enter the correct path"
fi

[root@localhost ~]# sh b.sh
 Check whether the directory exists. Please enter the directory:/etc
 Directory exists

2.3. Multi branch structure

Compared with single branch and double branch if statements, the structure of multi branch if statements can perform different operations according to multiple mutually exclusive conditions.

if [ Conditional judgment ]; then
	When the condition judgment is true, one or more commands can be executed
elif [ Conditional judgment formula II ]; then
	When the condition judgment is true, one or more commands can be executed
else	
	When the above conditions are not tenable, one or more commands can be executed
fi 		

Example 1:

According to the different test scores entered, we can distinguish three grades: excellent, qualified and unqualified.

[root@localhost ~]# vim c.sh

#!/bin/bash
read -p "Please enter your score(0-100) : " GE
if [ $GE -ge 85 ] && [ $GE -le 100 ]
then
echo "$GE Points, excellent!"
elif [ $GE -ge 70 ] && [ $GE -le 84 ]
then
echo "$GE Points, qualified!"
else
echo "$GE Points, unqualified!"
fi

[root@localhost ~]# sh c.sh
 Please enter your score(0-100) : 99
99 Points, excellent!
[root@localhost ~]# sh c.sh
 Please enter your score(0-100) : 79
79 Points, qualified!
[root@localhost ~]# sh c.sh
 Please enter your score(0-100) : 59
59 Points, unqualified!

Example 2:

Judge document category

[root@localhost ~]# vim d.sh

#!/bin/bash
read -p "Enter the file to identify:" name
if [ -d $name ] ;then
echo "This is a directory"
elif [ -f $name ];then
echo "This is a file"
elif [ -b $name ];then
echo"This is a device file"
else
echo "Unable to determine file category"
fi

[root@localhost ~]# sh d.sh
 Enter the file to identify:/etc
 This is a directory
[root@localhost ~]# sh d.sh
 Enter the file to identify:/etc/yum.conf
 This is a file
[root@localhost ~]# sh d.sh
 Enter the file to identify:root
 Unable to determine file category

2.4. Nested if statement

Example 1:

Determine whether the httpd service is started

Judge whether to start

If start ----- output is started

If it is not started ------ judge whether to install ------ if it is installed ------ start

If not installed ------ install ------ if the installation is successful ------ start

If the installation is not successful ---- an error is reported

root@localhost ~]# vim e.sh

#!/bin/bash

ps -aux | grep httpd | grep -v grep
if [ $? -ne 0 ];then
       if [ "$(rpm -q httpd)" == "Package not installed httpd" ];then
       yum install httpd -y
       systemctl start httpd
       else
       systemctl start httpd
       fi
else
    echo "httpd Service started" 
fi

[root@localhost ~]# sh e.sh 
root      11870  0.6  0.1 224072  5044 ?        Ss   15:05   0:00 /usr/sbin/httpd -DFOREGROUND
apache    11874  0.0  0.0 226156  3112 ?        S    15:05   0:00 /usr/sbin/httpd -DFOREGROUND
apache    11875  0.0  0.0 226156  3112 ?        S    15:05   0:00 /usr/sbin/httpd -DFOREGROUND
apache    11876  0.0  0.0 226156  3112 ?        S    15:05   0:00 /usr/sbin/httpd -DFOREGROUND
apache    11877  0.0  0.0 226156  3112 ?        S    15:05   0:00 /usr/sbin/httpd -DFOREGROUND
apache    11878  0.0  0.0 226156  3112 ?        S    15:05   0:00 /usr/sbin/httpd -DFOREGROUND
httpd Service started

3, case statement

Case statement can make the structure of script program more clear and hierarchical. It is often used in the script of service startup, restart and stop. Some services do not provide this control script and need to be written with case statement.

The case statement is mainly applicable to the following situations: a variable has multiple values, and different command sequences need to be executed for each value. This situation is very similar to multi branch if statements, except that if statements need to judge multiple different conditions, while case statements only judge the different values of a variable.
 

Format:
case Variable name in
 Mode 1)
	Command sequence
    ;;
Mode 2)
	Program segment
	;;
*)
	Other program execution segments that do not contain the content of the first variable and the content of the second variable
	Default segment
	;;
esac

Note:

  • The first mock exam must be case, and each mode must end with a single right bracket (in).

  • Double semicolon ";" Indicates the end of the command sequence.

  • In the pattern string, square brackets can be used to represent a continuous range, such as "[0-9]"; You can also use the vertical bar | to represent or, such as a|b.

  • The last () represents the default mode, where is equivalent to a wildcard.

Example 1:

Check the character type entered by the user

[root@localhost ~]# vim f.sh

#!/bin/bas

read -p "Please enter a character and press Enter Key confirmation:" KEY
case "$KEY" in
[a-z] | [A-Z])
echo "You entered letters"
;;
[0-9])
echo "You entered a number"
;;
*)
echo "You entered spaces or special characters"
esac


[root@localhost ~]# sh f.sh k
 Please enter a character and press Enter Key confirmation:k
 You entered letters
[root@localhost ~]# sh f.sh 
Please enter a character and press Enter Key confirmation:5
 You entered a number
[root@localhost ~]# sh f.sh  
Please enter a character and press Enter Key confirmation: 
You entered spaces or special characters

Example 2:

[root@localhost ~]# vim g.sh

#!/bin/bash
read -p "Please enter your score:" score
case $score in
100 )
echo "Xiuer!"
;;
9[0-9])
echo "$score Score, copy 10 times!"
;;
[78][0-9])
echo "$score Score, copy 20 times!"
;;
6[0-9])
echo "$score Score, copy 30 times!"
;;
[0-9]|[1-5][0-9])
echo "$score Score, copy all 30 times!"
;;
*)
echo "Incorrect input!"
esac

[root@localhost ~]# sh g.sh 
Please enter your score:100
 Xiuer!
[root@localhost ~]# sh g.sh 
Please enter your score:91
91 Score, copy 10 times!
[root@localhost ~]# sh g.sh 
Please enter your score:78
78 Score, copy 20 times!
[root@localhost ~]# sh g.sh 
Please enter your score:65
65 Score, copy 30 times!
[root@localhost ~]# sh g.sh 
Please enter your score:50
50 Score, copy all 30 times!
[root@localhost ~]# sh g.sh 
Please enter your score:1000
 Incorrect input!

4, Summary

(1) Syntax of conditional test: file test, integer value comparison, string comparison and logic test.
(2) Syntax of if conditional statements: single branch, double branch and multi branch.
(3) The syntax of case multi branch statements.

Topics: Linux