Writing shell scripts using the IF statement

Source: Internet
Author: User
Tags first string disk usage

Tag: Shell script if statement Yang Shufan Shell $?

In a simple shell script, each statement is executed sequentially in order to automate the batch process. However, a single sequential structure makes scripting less intelligent and difficult to handle for more flexible system tasks. By correctly using the IF statement, the shell script has certain judgment ability to accomplish different task management according to different conditions.


Conditional Test Action

For a shell script to have some intelligence, you must differentiate it from what you are doing under different conditions. For example, send an alarm message when disk usage exceeds 95%, etc.

A special test tool can be used to test a specific condition and determine whether the condition is true based on the return value ($?), and the return value of 0 indicates that the condition is true.

The format for using the Test command is as follows:

Format one: Test condition expression

Format two: [Conditional expression]

Typically, using format two is more of a programming habit, but the square brackets and conditional expressions require at least one space to separate


1. File Testing

File testing refers to the specified path name, determine whether the corresponding file or directory, is readable, writable, executable. The common operating options are as follows:

-D: Test for Catalog (directory)

-F: Test for file

-E: Test whether the directory or file exists (Exist)

-R: Tests whether the current user has permission to read (read)

-W: Tests whether the current user has permission to write (write)

-X: Tests whether the current user has permission to execute (excute)


2. Integer value comparison

The integer value comparison refers to the relationship between the first number and the second number according to the specified two integer values, and the common operation options are as follows:

-eq: The first number equals the second number

-ne: The first number is not equal to the second number

-GT: The first number is greater than the second number

-LT: The first number is less than the second number

-ge: The first number is greater than or equal to the second number

-le: The first number is less than or equal to the second number


3. String comparisons

String comparisons typically detect user input, whether the system environment meets the criteria, and the common operating options are as follows:

=: The first string is the same as a second string

! =: The first string is not the same as a second string

-Z: Detects if a string is empty, and a variable that is not defined or given a null value is treated as an empty string


4. Logic Test

Logical testing refers to the determination of dependencies between two or more conditions, and the common logic test operations are as follows:

&&: Logical AND, the return value of the entire test command is 0 only if both the first and the two conditions are true. ,&& can be changed to-a when using the test command

|| : Logical OR, the return value of the entire test command is 0, as long as one of the previous conditions is established. When using the Test command, | | Can be changed to-O

! : Logical No, the return value of the entire test command is 0 only if the specified condition is not true




Structure of the IF statement

In a shell script, the IF statement is the most commonly used process control method that is used to test the structure based on the specified criteria, performing different actions, respectively, if ... So...... )

1. Single-branch if statement

Case 1: determine if the/media/cdrom directory exists and create a new directory if it does not exist

[Email protected] ~]# vim dir.sh#!/bin/bashdir= "/media/cdrom/" if [!-D $DIR]then mkdir-p $DIRfi


Case 2: determine whether the current user is root, if not the root user error, and exit the script, when the root user executes the script, if statement does not execute, the normal execution of the script code after fi

[[email protected] ~]# vim Root.sh#!/bin/bashif ["$USER"! = "root"]then echo "error: Non-root user, insufficient permissions" Exit 1fifdisk-l/dev/s Da


2. Dual-Branch if statement

Case 1: write a test connectivity script that gives the appropriate hints based on the display results

[[email protected] ~]# vim pinghost.sh#!/bin/bashping-c 3-i 0.2-w 3 $ &>/dev/nullif [$?-eq 0]then Echo] Host is up. " else echo "Host is down." Fi[[email protected] ~]#. pinghost.sh 192.168.4.11Host 192.168.4.11 is up. [Email protected] ~]#. pinghost.sh 192.168.4.13Host 192.168.4.13 is down.


Case 2: The script detects whether the VSFTPD service is running, and if it is running, lists its listening address, PID number, or output hint "WARNING: VSFTPD service is not available! ”

[[email protected] ~]# vim ftpd.sh#!/bin/bash/etc/init.d/vsftpd status &>/dev/nullif [$?-eq 0]then echo "listening ground Address: $ (netstat-anpt | grep vsftpd | awk ' {print $4} ') "echo" Process pid:$ (pgrep-x vsftpd) "Else echo" WARNING: VSFTPD service is not available! "Fi[[email protected] ~]# sh ftpd.sh warning: VSFTPD service is not available! [[email protected] ~]#/etc/init.d/vsftpd start[[email protected] ~]# sh ftpd.sh listener address: 0.0.0.0:21 process pid:986


3. Multi-Branch If statement

Case: write a script that distinguishes between good, qualified, and failing grades according to the input test score

[[email protected] ~]# vim gradediv.sh#!/bin/bashread-p "Please enter your score (0-100):" Gradeif [$GRADE-ge] && [$GRADE- Le [] then echo "$GRADE points! Excellent "elif [$GRADE-ge] && [$GRADE-le] then echo" $GRADE points, qualified "else echo" $GRADE points? Unqualified "Fi[[email protected] ~]# sh gradediv.sh Please enter your score (0-100): 8989 points! Excellent





Writing shell scripts using the IF statement

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.