Shell script if conditional statement

Posted by bobbythenewb on Sat, 12 Oct 2019 00:10:37 +0200

Condition testing

Test command: Test whether a particular expression is valid. When the condition is valid, the return value of the test statement is 0, otherwise it is another value.

Format 1: test conditional expression
Format 2: [conditional expression] (note that there is a space between the brackets and the expression)

Document testing:

Format: [Operator file or directory] (Note that there are spaces between parentheses and expressions)

Common test operators:

- d: Testing for Directory
 - e: Testing whether a directory or file exists (Exist)
- f: Test for File
 - r: Test whether the current user has permission to read (Read)
- w: Test whether the current user has permission to write (Write)
- x: Test whether the current user has permission to execute (eXcute)
[root@localhost ~]# [ -d /media/cdrom ]
[root@localhost ~]# echo $?
0                                                                                    //Return 0 to indicate the condition is valid
[root@localhost ~]# [ -d /media/cdrom/Server ]
[root@localhost ~]# echo $?
1                                                                                   //Return 1 denotes that the condition is not valid
[root@localhost ~]# [-d/media/cdrom] & & echo "YES"//"&" indicates that when the current test is valid, the following commands are executed
YES
[root@localhost ~]# [ -r /media/cdrom ]
[root@localhost ~]# echo $?
1
[root@localhost ~]# [ -w /media/cdrom ]
[root@localhost ~]# echo $?
1
[root@localhost ~]# [ -x /media/cdrom ]
[root@localhost ~]# echo $?
1
[root@localhost ~]#

Integer numerical comparison:

Format: [Integer 1 Operator Integer 2] (Note that there are spaces between parentheses and expressions)

Common test operators:

- eq: Equal
 - ne: Not Equal
 - gt: greater than (Greater Than)
- lt: Lesser Than
 - le: Lesser or Equal
 - ge: greater than or equal to (Greater or Equal)
[root@localhost ~]# who | wc -l
7
[root@localhost ~]# [ $(who | wc -l) -gt 5 ] && echo "Too many."
Too many.
[root@localhost ~]# [ $(who I wc -l) -ge10 ] && echo ">= 10."

String and Logic Testing

String comparison:

Format 1: [String 1 = String 2] or [String 1! = String 2] ("!" means negative)
Format 2: [- z string]

Common test operators:

= The string content is the same
 !=: The contents of the strings are different, and the! Sign means the opposite.
- z: String content is empty
[root@localhost ~]# echo $LANG
zh_ CN.UTF-8
[root@localhost ~]# [$LANG!= "en.US"] & echo "Not en.US"//Test the current language environment
Not en.US
[root@localhost ~]# Read-p "Overwrite existing files (yes/no)?" ACK // Test whether the read string is yes
//Do you overwrite existing files (yes/no)?
[root@localhost ~]# [$ACK = yes"I & echo" coverage“
//cover

Logic testing:

Format 1: [Expression 1] Operator [Expression 2]
Format 2: Command 1 Operator Command 2

Common test operators:

- a or & Logic and the meaning of "and"
- o or |: Logic or the meaning of "or"
Logic: no
[root@localhost ~]#[ -d /etc ] && [ -r /etc ] && echo"You can open it"
[root@localhost ~]#[ -d /etc ] II [ -d /home ] && echo"ok"

if statement

if single branch statement

Basic format:

if  Conditional test operation
    then  Command sequence
fi

Example: Judge the mount point directory and create it automatically if it does not exist.

[root@localhost ~]# vim chkmountdir.sh
#!/bin/bash
MOUNT_DIR="/media/cdrom/"                 //Execute when directory does not exist
if [ ! -d $MOUNT_DIR ]
then
    mkdir -p $MOUNT_ DIR
fi

if double branch statement

Basic format:

if  Conditional test operation
    then  Command Sequence 1
    else  Command Sequence 2
fi

Example: Determine whether the target host is alive or not, and display the test results.

[root@localhost ~]# vim pinghost.sh
#!/bin/bash
ping -c 3 -i 0.2 -W 3 $1 &> /dev/null        //- Number of c packets, - i interval seconds, - W waiting time
if [ $? -eq 0 ]                                               //Judging the detection result of ping command
then
    echo "Host $1 is up."                         
else
    echo "Host $1 is down."
fi

if multi-branch statement

Basic format:

if conditional test operation 1
    The n command sequence 1
 Elf conditional test operation 2
    The n command sequence 2
else
    Command Sequence 3
fi

Examples: Judging the scoring range, we can divide it into three grades: excellent, qualified and unqualified.

[root@localhost ~]# vim gradediv.sh
#!/bin/bash
read -p "Please enter your score(0-100): " GRADE
if [ $GRADE -ge 85 ] && [ $GRADE -le 100 ]
then
    echo "$GRADE Distinction, excellence!"
elif [ $GRADE -ge 70 ] && [ $GRADE -le 84 ]
then
    echo "$GRADE Sub standard!"
else
    echo "$GRADE Score, disqualification!"
fi

if nested statement

In fact, nested structure is in the first three structures, plus a layer of if judgment statement. Let me illustrate it directly with an example. The main function of this Shell script is to make a judgment when you input the score, and enter the final when the input score is less than 10 seconds (including 10 seconds), otherwise it will be eliminated. After entering the finals, they will be prompted to input gender for judgment and grouping. If the gender is male, they will be grouped into men's group, otherwise they will be grouped into women's group.

[root@localhost opt]# vim group.sh
#!/bin/bash
read -p "Please enter your score:" sco
if [ $sco -le 10 ]
then
        echo "Congratulations on entering the finals!"
        read -p "Please enter your gender:" sex
        if [ $sex = "male" ]
        then
                echo "You're in the men's group!"
        else
                echo "You're in the women's group!"
        fi
else
        echo "I'm sorry you were eliminated!"
fi

The results are as follows:

[root@localhost opt]# chmod +x group.sh 
[root@localhost opt]# ./group.sh 
Please enter your score:9
 Congratulations on entering the finals!
Please enter your gender: male
 You're in the men's group!
[root@localhost opt]# ./group.sh 
Please enter your score:9
 Congratulations on entering the finals!
Please enter your gender:
You're in the women's group!
[root@localhost opt]# ./group.sh 
Please enter your score:11
 I'm sorry you were eliminated!
[root@localhost opt]# 

Topics: Linux vim shell less