Basic Judgment of Shell Scripts

I. Conditional testing

Format 1: test conditional expression
 Format 2: [Conditional expression]

II. Document testing

    -d: Test if it is a directory( Directory)
    -e: Test the existence of a directory or file( Exist)
    -f: Test whether it is a file or not( 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 ~]# Test-d/etc/yum//test/etc/yum is a directory
[root@localhost ~]# echo $?// / The last command execution state 0 is normal execution, or zero is error.
    0
[root@localhost ~]# Test-f/etc/yum//test/etc/yum is a file
[root@localhost ~]# echo $?
    1
[root@localhost ~]# Test-e/etc/yum//test/etc/yum
[root@localhost ~]# echo $?
    0

Integer test

    - 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) - GT 10] & echo "a bit too much!"// Statistics of current users
    A little too much!

IV. String comparison

    Format 1: [1 = 2]
    Format 2: [-z 2]

    == The string content is the same
    !=: The contents of the strings are different!!!
    - z: String content is empty

V. Logic Testing

    -a or&&: Logic and the Meaning of "and"
    -o or||:  Meaning of Logic or "or"
    !: Logical No

[root@localhost ~]# [! - e/opt/abc] & & mkdir/opt/abc//opt/abc does not exist and I will create this directory
[root@localhost ~]# ls /opt
abc  rh

6.if statement single branch

![](https://s1.51cto.com/images/blog/201910/09/a9f39959fb7e9ee3c80634b282a7ac5d.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)
#!/bin/bash
mulu="/etc/ccc"  
if [ ! -d $mulu ] 
then
    mkdir -p $mulu
fi

7.if double branch statement

#!/bin/bash
ping -c 3 -i 0.2 -W 3 $1 &>/dev/null
if [ $? -eq 0 ]
then
    echo "Host $1 is up "
else
    echo "Host $1 is down "
fi
#- C sends data packets, - 0.2 every two seconds - W 3 replies to all output to this useless directory

[root@localhost ~]# source test.sh
    Host  is down 

8.if multi-branch and nested statements

#!/bin/bash
#A running race that enters the final within 10 seconds and is divided into men's or women's groups after entering the final.
read -p "Please enter your game time." tim
if [ $stim -lt 10 ]
then
    echo "Enter the finals"
    read -p "Please enter your gender(male/female) " sex
    if [ $sex = "male" ]
        then
            echo "Enter the Men's Group"
    else
            echo "Enter the Women's Group"
    fi
else "Eliminated"
fi

Keywords: Linux yum

Added by batterdmooie on Thu, 10 Oct 2019 01:28:02 +0300