[Shell] Conditional judgment and Process Control: If, case, for, while, until

Source: Internet
Author: User
Tags case statement file permissions



"Conditional judgment"



1. Judging by file type



-B file to determine if the file exists and is a block device file (is a block device file is true)



-c file to determine if the file exists and is a character device file (the character device file is true)



- D file determine if the file exists and is a directory file (the directory is true)



- E file determine if the file exists (exists as true)



- F file determine if the file exists and is a normal file (the normal file is true)



-l file to determine if the file exists and is a symbolic link file (the symbolic link file is True)



-P file to determine if the file exists and is a pipe file (the pipe file is true)



-S file to determine if the file exists and is non-null (non-NULL is true)



-S file to determine if the file exists and is a socket file (the socket file is true)






Two kinds of judging formats:



①TEST-E/root/install.log



②[-e/root/install.log]






[-f/root/install.log] && echo ' Yes ' | | Echo ' No '






2. According to the file permissions to judge (do not distinguish between the owner, group)



- R file determine if the file exists and has Read permission (Read permission is true)



- W file determine if the file exists and has Write permission (Write permission is true)



- x File determine if the file exists and has execute permission (with Execute permission is true)



-u file to determine if the file exists and has Suid permissions (suid permissions are true)



-G file to determine if the file exists and has Sgid permissions (Sgid permissions are true)



-K file to determine if the file exists and has Sbit permissions (sbit permissions are true)






3. Compare between two files



Files 1-nt File 2 Determine if the modification time of file 1 is newer than file 2 (if the new is true)



Files 1-ot File 2 Determine if the modification time of file 1 is greater than the old file 2



Files 1-ef file 2 Determine whether the file 1 is the same as the inode number of file 2, which can be understood as whether two files are the same file. This judgment is a good way to judge hard links.






4. Comparison of two integers



Integer 1-EQ integer 2 to determine if the integer 1 is equal to the integer 2 (True for equality)



Integer 1-ne integer 2 to determine if the integer 1 is not equal to the integer 2 (the inequality is true)



Integer 1-GT integer 2 to determine if integer 1 is greater than integer 2 (greater than true)



Integer 1-LT integer 2 to determine if integer 1 is greater than integer 2 (less than true)



Integer 1-ge integer 2 Determines whether the integer 1 is greater than or equal to the integer 2 (greater than or equal to true)



Integer 1-le integer 2 Determines whether the integer 1 is less than or equal to the integer 2 (less than or equal to true)






[1 eq 2] && echo ' Yes ' | | Echo ' No '






5. The judgment of the string



-Z string to determine whether the string is empty (returns true for null)



-N string to determine whether the string is non-null (non-null return TRUE)



String 1 = = String 2 Determines if string 1 and string 2 are equal (returns true for equality)



String 1! = String 2 Determines if string 1 is not equal to string 2 (not equal returns True)






Name=chen



[-Z "$name"] && echo ' Yes ' | | Echo ' No '






6. Multiple conditional judgments



Judge 1-a judgment 2 logic and judgment 1 and judgment 2 are established, the final result is true



Judging 1-o judgment 2 logic or, judging 1 and judging 2 has a set up, the final result is true



! Judge the logic not, make the original judgment to reverse






A=24



[-N "$a"-a "$a"-gt] && echo ' Yes ' | | Echo ' No '






"Process Control-if statement"



1. Single-branch if condition statement

if [conditional judgment]; then
    program
fi
if test -z "$ ac_version"; then?
    program
fi
or

if [condition judgment type]
    then
        program
fi
 

note:

    ① If starts, fi ends

    ② [Condition Judgment] is to use the test command to judge, so there must be a space between the brackets and the conditional judgment

    ③ Then followed by the program that is executed after the conditions are met, you can put it after [] and use ";" to split it, or you can write it on a new line, you don't need ";" anymore.

 

#! / bin / bash
# Statistics root partition usage

rate = $ (df -h | grep "/ dev / sda3" | awk ‘{print $ 5}’ | cut -d "%" -f1) # Assign the root partition usage rate as a variable value to the variable rate

if [$ rate -ge 80]; then
    echo "Warning! / dev / sda3 is full!"
fi
 

2. Double branch if conditional statement

if [condition judgment type]
    then
        Procedures to be executed when the conditions are met
    else
        When the condition is not established, another program to be executed
fi
 

#! / bin / bash
# Backup mysql database

ntpdate asia.pool.ntp.org &> / dev / null # Synchronize the system time (Internet connection required)

date = $ (date +% y% m% d) # Assign the current system time to the variable date in the format of "year, month and day"

size = $ (du -sh / var / lib / mysql) # Statistics the size of the mysql database and assign the size to the size variable

if [-d / tmp / dbbak]
    then
        echo "Date: $ date!"> /tmp/dbbak/dbinfo.txt

        echo "Data size: $ size" >> /tmp/dbbak/dbinfo.txt

        cd / tmp / dbbak

        tar -zcf mysql-lib- $ date.tar.gz / var / lib / mysql dbinfo.txt

        &> / dev / null # discard all output

        rm -rf /tmp/dbbak/dbinfo.txt # Unscrew and kill donkey
    else
        mkdir / tmp / dbbak
        ...
fi
 

#! / bin / bash
# Determine whether Apache is started (install nmap first: rpm -ivh http://nmap.org/dist/nmap-4.68-1.i386.rpm)

port = $ (nmap -sT 192.168.1.156 | grep tcp | grep http | awk ‘{print $ 2}’) # Use the nmap command to scan the server and intercept the status of the apache service and assign the variable port

if ["$ port" == "open"]
    then
        echo "$ (date) httpd is ok!" >> /tmp/httpd-acc.log # If the status is normal, append to the log
    else
        /etc/rc.d/init.d/httpd start &> / dev / null # discard all output
        echo "$ (date) httpd reboot!" >> /tmp/httpd-err.log # Restart record is appended to the error log
fi
 

3. Multi-branch if conditional statement

if [condition judgment type 1]
    then
        When condition judgment formula 1 is established, program 1 is executed
    elif [conditional judgment formula 2]
        then
            When the conditional judgment formula 2 is established, the program 2 is executed
    ... more judgment ...
    else
        When all conditions are not established, the last execution of this procedure
fi
 

#! / bin / bash
# Determine what file the user entered

read -p "Please input a filename:" file # Receive keyboard input and assign the variable file

if [-z "$ file"]
    then
        echo "Error, please input a filename"
        exit 1
    elif [! -e "$ file"] # Determine whether the value of file exists
        then
            echo "Your input is not a file!"
            exit 2
    elif [-f "$ file"] # Determine whether the value of file is an ordinary file
        then
            echo "$ file is a regular fie!"
    elif [-d "$ file"]
        then
            echo "$ file is a directory!"
    else
        echo "$ file is an other file!"
fi
 

[Flow control-case statement]

Multi-branch case conditional statement: The case statement can only judge one kind of conditional relationship, while the if statement can judge many kinds of conditional relationship.

case $ variable name in
    "Value 1")
         If the value of the variable is equal to the value 1, the program 1 is executed
         ;;
    "Value 2")
         If the value of the variable is equal to the value 2, the program 2 is executed
         ;;
    *)
         If the value of the variable is not the above value, then execute this procedure
         ;;
esac
 

#! / bin / bash
# Determine user input

read -p "Please choose yes / no" -t 30 cho

case $ cho in
    "yes")
         echo "You choose yes"
         ;;
    "no")
         echo "You choose no"
         ;;
    *)
         echo "You choose none"
         ;;
esac
 

[Flow control-for loop]

Syntax 1:

for variable in value 1 value 2 value 3 ...; do
    program
done
Syntax 2:

for ((initial value; cycle control condition; variable change))
    do
        program
    done
 

#! / bin / bash
# Print Time

for time in morning noon afternoon evening; do
    echo "This time is $ time"
done

for i in 1 2 3 4; do
    echo $ i
done
 

#! / bin / bash
# Batch unzip script

cd / lnmp
ls * .tar.gz> ls.log

for i in $ (cat ls.log); do
    tar -zxf $ i &> / dev / null
done
rm -rf /lnmp/ls.log
 

#! / bin / bash
# Summation

s = 0
for ((i = 1; i <= 100; i ++)); do
    s = $ (($ s + $ i))
done

echo "The sum of 1 + 2 + 3 + ... + 100 is: $ s"
 

#! / bin / bash
# Add a specified number of users in batches

read -p "Please input user name:" -t 30 name
read -p "Please input the number of users:" -t 30 num
read -p "Please input the password of users:" -t 30 pass

# -a is used for continuous multiple conditions judgment
if [! -z "$ name" -a! -z "$ num" -a! -z "$ pass"]
    then
        y = $ (echo $ num | sed ‘s / ^ [0-9] * $ // g’) # replace any number with empty
        if [-z "$ y"] # If the value of y is empty, num is a number
            then
                for ((i = 0; i <= $ num; i ++))
                    do
                        / usr / sbin / useradd $ name $ i &> / dev / null
                        echo $ pass | / usr / bin / passwd --stdin "$ name $ i" &> / dev / null
                    done
        fi
fi
 

[Flow Control-while and until loop]

The while loop is a conditional loop. As long as the conditional judgment formula is established, the loop will continue until the conditional judgment formula is not established.

while [conditional judgment]
    do
        program
    done
 

#! / bin / bash
# Example usage

while [$ # -gt 0]; do
    case "$ #" in
    3)
        echo "The first parameter is $ 1, the number of parameters is $ #"
        ;;
    4)
        echo "The first parameter is $ 1, the number of parameters is $ #"
        ;;
    *)
        echo ‘What happened’
        ;;
    esac # corresponds to case to form a case statement in the form of if and fi

    case "$ #" in
    abc)
        ... ;;
    esac
    shift # Use the shift command to move the positional parameter to the left
done
Run as: ./example.sh 3 4 5

 

until loop: Contrary to while loop, when until loop, as long as the condition judgment is not true, it will loop and execute the loop program. Once the loop condition is established, the loop is terminated.

#! / bin / bash

i = 1
s = 0
until ["$ i" -gt 100] # loop until the value of the variable i is greater than 100 to stop the loop
    do
        s = $ (($ i + $ s))
        i = $ (($ i + 1))
    done

echo "The sum is: $ i"
 

【to sum up】

Shell is applicable: help administrators reduce repetitive operations or operation and maintenance operations, not suitable for complex calculation occasions.

How to build programming ideas: learn, practice, and know what the program does for you.

[Shell] Condition judgment and flow control: if, case, for, while, until 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.