[Excerpt] shell script Condition Statement

Source: Internet
Author: User
Tags sorts
Chapter 3 condition statements
Directory
7.1. Introduction to if
7.1.1. Summary
7.1.2. Simple Application of if
7.2. More advanced if usage
7.2.1. if/then/else Structure
7.2.2. if/then/elif/else Structure
7.2.3. if nested statement
7.2.4. boolean operation
7.2.5. Use the exit statement and if
7.3. Use case statements
7.3.1. Simple Conditions
7.3.2. Example of initial script
7.4. Summary
7.5. Exercise
Summary
In this chapter, we will discuss conditions used in Bash scripts, including the following topics:
If statement
Command exit status
Compare and test input and files
If/then/else Structure
If/then/elif/else Structure
Use and test location parameters
Nested if statement
Boolean expression
Use case statements
7.1. Introduction to if
7.1.1. Summary
Sometimes you need to specify whether or not the shell script is successful or not to implement different processes. The if structure allows you to specify such conditions.
The simplest syntax of the if command is:
If TEST-COMMANDS; then CONSEQUENT-COMMANDS; fi
After the TEST-COMMAND is executed and its return status is 0, the CONSEQUENT-commands command is executed. The returned status is the exit status of the last command, or 0 if no conditions are true.
TEST-COMMAND often includes comparison tests of numbers and strings, but it can also be any COMMAND that returns the status 0 when the result is successful or some other statuses when the result is failed. One-dimensional expressions are often used to check the file status. If the FILE parameter is in the format of/dev/fd/N for a certain element, check the FILE descriptor "N ". Stdin, stdout, stderr, and their respective file descriptors can also be used for testing.
7.1.1.1. And if expressions
The following table contains an overview of the TEST-COMMAND or COMMAND list, called "element primaries. These primaries are placed in square brackets to represent a test of a conditional expression.
Table 7.1. Primary Expression
Primary meaning
[-A FILE] true if the FILE exists.
[-B FILE] If the FILE exists and is a special block FILE, it is true.
[-C FILE] If the FILE exists and is a special word FILE, it is true.
[-D FILE] If the FILE exists and is a directory, it is true.
[-E FILE] If the FILE exists, it is true.
[-F FILE] If the FILE exists and is a normal FILE, it is true.
[-G FILE] If the FILE exists and the SGID has been set, it is true.
[-H FILE] If the FILE exists and is a symbolic connection, it is true.
[-K FILE] true if the FILE exists and the stick bits have been set.
[-P FILE] If the FILE exists and is a name pipe (F If O), it is true.
[-R FILE] true if the FILE exists and is readable.
[-S FILE] If the FILE exists and the size is not 0, it is true.
[-T FD] It is true if the file descriptor FD is opened and points to a terminal.
[-U FILE] If the FILE exists and SUID (set user ID) is set, it is true.
[-W FILE] true if the FILE exists and is writable.
[-X FILE] true if the FILE exists and is executable.
[-O file] true if the FILE exists and belongs to a valid user ID.
[-G file] true if the FILE exists and belongs to a valid user group.
[-L file] If the FILE exists and is a symbolic connection, it is true.
[-N file] If FILE exists and has been mod, it is true if ied since it was last read.
[-S file] If the FILE exists and is a socket, it is true.
[FILE1-nt FILE2] If FILE1 has been changed more recently than FILE2, or if FILE1FILE2 does not is true. Exists and
[FILE1-ot FILE2] True if FILE1 is older than FILE2, or if FILE2 exists and FILE1 does not exist.
[FILE1-ef FILE2] True if FILE1 and FILE2 point to the same device and node number.
[-O OPTIONNAME] true if the shell option "OPTIONNAME" is enabled.
[-Z STRING] "STRING" is true if its length is zero.
If the length of [-n STRING] or [STRING] "STRING" is non-zero, it is true.
[STRING1 = STRING2] If the two strings are the same. "=" May be used instead of "=" for strict POSIX compliance is true.
[STRING1! = STRING2] true if the strings are not equal.
[STRING1 <STRING2] True if "STRING1" sorts before "STRING2" lexicographically in the current locale.
[STRING1> STRING2] True if "STRING1" sorts after "STRING2" lexicographically in the current locale.
[ARG1 OP ARG2] "OP" is one of-eq,-ne,-lt,-le,-gt or-ge. these arithmetic binary operators return true if "ARG1" is equal to, not equal to, less than, less than or equal to, greater than, or greater than or equal to "ARG2 ", respectively. "ARG1" and "ARG2" are integers.

The expression can be listed in descending order by combining the following operators: listed in decreasing order of precedence:
Table 7.2. Combined expressions
Operation results
[! EXPR] True if EXPR is false.
[(EXPR)] returns the value of EXPR. This can be used to ignore normal operator priorities.
[EXPR1-a EXPR2] True if EXPR1 and EXPR2 are all true.
[EXPR1-o EXPR2] True if EXPR1 or EXPR2 is true.

The [(or test) built-in command uses a series of parameter-based rules for conditional expressions to evaluate values. For more information about this topic, see the Bash document. Just as if you end with fi, you must end with ">" after the condition column is complete.
7.1.1.2. commands followed by the then statement
CONSEQUENT-COMMANDS lists any valid unix commands, any executable programs, any executable shell scripts, or any shell statements following the then statement, except fi .. It is important to remember that then and fi are considered separate statements in shell. Therefore, they are separated by semicolons when used on the command line.
In scripts, different parts of the if statement are normally well separated. Here are some simple examples:
7.1.1.3. Check the file
The first example checks whether a file exists:
Anny ~> Cat msgcheck. sh #! /Bin/bashecho "This scripts checks the existence of the messages file. "echo" Checking... "if [-f/var/log/messages] then echo"/var/log/messages exists. "fiechoecho "... done. "anny ~> ./Msgcheck. shThis scripts checks the existence of the messages file. Checking.../var/log/messages exists... done.
7.1.1.4. Check shell options
Add it to your Bash configuration file:
# These lines will print a message if the noclobber option is set: if [-o noclobber] then echo "Your files are protected against accidental overwriting using redirection." fi
Environment
The preceding example starts after the command line is entered:
Anny ~> If [-o noclobber]; then echo; echo "your files are protectedagainst overwriting."; echo; fiyour files are protected against overwriting. anny ~>

However, if you use environment-dependent testing, you may not need to enter the same command in the script because the script will open a new one, shell with no expected variables or options set.

7.1.2. Simple Application of if
7.1.2.1. Test exit status
? The variable contains the exit status of the previously executed command (the most recently completed foreground process ).
The following example shows a simple test:
Anny ~> If [$? -Eq 0] More input> then echo 'That was a good job! 'More input> fiThat was a good job! Anny ~>

The following example demonstrates that TEST-COMMANDS can be any UNIX command with a return and exit status, and then if it returns a zero exit status again:
Anny ~> If! Grep $ USER/etc/passwdMore input> then echo "your user account is not managed locally"; fiyour user account is not managed locallyanny> echo $? 0 anny>

The same result can be obtained as follows:
Anny> grep $ USER/etc/passwdanny> if [$? -Ne 0]; then echo "not a local account"; finot a local accountanny>

7.1.2.2. Comparison of numbers
The following example compares values:
Anny> num = 'wc-l work.txt 'anny> echo $ num201anny> if ["$ num"-gt "150"] More input> then echo; echo "you 've worked hard enough for today. "More input> echo; fiyou 've worked hard enough for today. anny>

This script is executed by cron every Sunday. If the number of weeks is even, he will remind you to clear the garbage bins:
#! /Bin/bash # Calculate the week number using the date command: WEEKOFFSET = $ [$ (date + "% V") % 2] # Test if we have a remainder. if not, this is an even week so send a message. # Else, do nothing. if [$ WEEKOFFSET-eq "0"]; then echo "Sunday evening, put out the garbage cans. "| email-s" Garbage cans out "your@your_domain.org
7.1.2.3. String comparison
An example of testing the user ID by comparing strings:
If ["$ (whoami )"! = 'Root']; then echo "You have no permission to run $0 as non-root user." exit 1; fi
With Bash, you can shorten the structure. The simplified structure of the above tests is as follows:
["$ (Whoami )"! = 'Root'] & (echo you are using a non-privileged account; exit 1)
Similar to the "&" expression that is executed if the test is true, "|" specifies that the test is executed if the test is false. Similar to the "&" expression, which specifies the action taken when two test conditions are true, "|" indicates the action taken when the test is false.
Regular Expressions can also be used in comparison:
Anny> gender = "female" anny> if [["$ gender" = f *] More input> then echo "Pleasure to meet you, Madame. "; fiPleasure to meet you, Madame. anny>

Real Programmers
Most programmers prefer the built-in test commands that share the same role as square brackets, such:
Test "$ (whoami )"! = 'Root' & (echo you are using a non-privileged account; exit 1)


See the information page for more module matching information about the Bash "(EXPRESSION)" and "[[EXPRESSION]" structures.




Shell if command parameter description
-B. returns true if the file exists and is a block file.
-C: returns true if the file exists and is a character file.
-D. If pathname exists and is a directory, true is returned.
-E: returns true if the file or directory specified by pathname exists.
-F returns true if the file exists and is a regular file
-G returns true if the file or directory specified by pathname exists and the SGID bit is set.
-H returns true if the file exists and is a symbolic link file. This option is invalid in some old systems.
-K. If a file or directory specified by pathname exists and a "Sticky" bit is set, the system returns the true value.
-P: returns true if the file exists and is a command pipeline.
-R: returns true if the file or directory specified by pathname exists and is readable.
-S: returns true if the file size is greater than 0.
-U returns true if a file or directory specified by pathname exists and SUID is set.
-W returns true if the file or directory specified by pathname exists and is executable. A directory must be executable for its content access.
-O returns true if a file or directory specified by pathname exists and the user specified by the valid user ID of the current process is owned by it.

Comparison character writing:
-Eq equals
-Ne is not equal
-Gt greater
-Lt is less
-Le is less than or equal
-Ge is greater than or equal
-Z empty string
* = Two equal characters
*! = Two characters
*-N non-empty string
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.