(027) The Shell branch if statement for Linux

Source: Internet
Author: User
Tags readable

Fundamentals of the ten-year OPS series-Linux

Zeng Lin

Contact: [Email protected]

Website: www.jplatformx.com

Copyright: Please do not reprint the article without permission

first, use the IF statement

Through the shell, we can write a shell script fragment that uses the IF statement. As shown below:

#!/bin/"if"  statementx=5if5then     echo"x equals 5"else    echo"  x doesn ' t equals 5"fi

Alternatively, you can enter the above code directly on the command line (slightly simplified), as shown in:

The syntax format for the IF statement is as follows:

if  Then     commands[elifthen    commands][Else    commands] if

In this syntax format, "command" can be a set of commands. At first glance it may seem a bit confusing. Before we get rid of this confusion, we must first understand how the shell determines the success and failure of a command.

Second, exit status

commands, including shell scripts and shell functions we write, send a value to the operating system, called exit status, after execution. This value is an 0~255 integer that indicates whether the command executed successfully or failed. By convention, a value of 0 indicates successful execution, and other numeric values indicate that the execution failed. The shell provides a parameter that can be used to detect the exit status. This parameter is $?. As shown in the following:

In this example, we executed the LS command two times. For the first time, the command executes successfully if the parameter "$?" is displayed. Value, you can see that the value is 0. The second time the LS command was executed, an error occurred, showing "$?" again. , this time the value is 2, indicating that the command encountered an error. Some commands use different exit values to diagnose errors, and when command execution fails, simply exit and send a digital 1.man manual often includes a paragraph titled "Exit Status", which describes the code used. The number 0 always indicates a successful execution.

The shell provides 2 very simple built-in commands that don't do anything except terminate execution with a 0 or 1 exit state. The "true" command always indicates a successful execution, and a "false" command always indicates an execution failure. As shown in the following:

We can use these two commands to see how the IF statement works. What the IF statement really does is evaluate the success or failure of the command.

When the command after the if execution succeeds, the command echo "it's true." is executed, and the command does not execute when the command execution fails after the IF. If there is a series of commands following the IF, then the evaluation is based on the results of the last command execution. As shown in the following:

Third, use the test command

So far, the command that is often used with if is test. The test command performs various checks and comparisons. There are two equivalent forms of this command:

  Test expression

and the more popular

  [Expression]

  The expression here is a formula, and the result is true or false. When this expression is true, the test command returns a 0 exit state, and when the expression is false the exit state of the test command is 1.

    1. File Expressions (expression)

The expressions in the following table show the expressions about the file. These file expressions are used to evaluate the status of a file.

File expression Conditions to become true
File1-ef File2 File1 and File2 have the same information node number (these two files are pointed to the same file via a hard link)
File1-nt File2 File1 than File2 new
File1-ot File2 File1 than file2 old
-B File File exists and is a block (device) files
-C file File exists and is a character (device) files
-D File File exists and is a directory
-E File File exists
-F File File exists and is an ordinary file
-G file File exists and the group ID is set
-G file File exists and belongs to valid group ID
-K File File exists and has a "sticky bit (sticky bit) attribute"
-L File File exists and is a symbolic link
-O File File exists and belongs to a valid user ID
-P File File exists and is a named pipe
-R File File exists and is readable (valid user has readable permission)
-S file File exists and its length is greater than 0
-S file File exists and is a network socket
-T FD FD is a directed-to-terminal/terminal-directed file descriptor that can be used to determine whether standard I/O/errors are redirected
-U file File exists and the setuid bit is set
-W File File exists and is writable (valid user has writable permission)
-X File File exists and is executable (valid user has execute/search permission)

The following code shows an example of using a file expression:

#!/bin/bash# Test-file: Evaluate the status of afileFILE=~/. BASHRCif[-E"$FILE"]; Then    if[-F"$FILE"]; Then        Echo "$FILE is a regular FILE."    fi      if[-D"$FILE"]; Then        Echo "$FILE is a directory."    fi      if[-R"$FILE"]; Then        Echo "$FILE is readable."    fi      if[ -W "$FILE"]; Then        Echo "$FILE is writable."    fi      if[-X"$FILE"]; Then        Echo "$FILE is executable/searchable."    fi  Else    Echo "$FILE does not exist"Exit1fiExit

There are two interesting places to note about the above script. First, be aware of how $file is referenced within an expression. Although the quotation marks are not required, this can prevent the argument from being empty. If the $file parameter extension produces a null value, an error will result (the operator is interpreted as a non-empty string, not an operator). Enclose the argument in quotation marks to ensure that the operator always follows a string, even if the string is empty. Second, note the exit command at the end of the script. This exit command accepts a separate optional parameter, which will be called the exit state of the script. When parameters are not passed, the exit state defaults to 0. Using the exit command in this way allows the script prompt to fail when the $file extension is a file name that does not exist. This exit command appears in the last line of the script. This way, when the script executes to the end, anyway, by default it terminates with exit status 0.

Similarly, the Shell function can return an exit state by including an integer argument in the return command. If you want to convert the above script to a shell function that can be used in a larger program, you can replace the exit command with the return command and get the desired behavior.

(027) The Shell branch if statement for Linux

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.