Bash shell if command parameter description

Source: Internet
Author: User
Tags case statement sorts
Abstract: This chapter discusses the conditions used in Bash scripts, including the following topics: if statement use command exit status comparison and test input and file if/then/else structure if/then/elif/else structure use and test position parameter nested if statement Boolean expression use case statement
7.1. Introduction to if
7.1.1. Sometimes you need to specify whether 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 TEST-COMMAND is executed and its return status is 0, then CONSEQUENT-COMMANDS 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. The following table lists the expressions used by the and if statements that form the TEST-COMMAND or COMMAND list, which is called the "element primaries. These primaries are placed in square brackets to represent a test of a conditional expression. Table 7.1. Significance of the Primary expression Primary
[-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. expressions can be listed in descending order by combining the following operators: listed in decreasing order of precedence: Table 7.2. combined expression operation effect
[! 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. the command CONSEQUENT-COMMANDS followed by the then statement 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 first example of a file to check whether a file exists: anny ~> Cat msgcheck. sh #! /Bin/bash echo "This scripts checks the existence of the messages file. "echo" Checking... "if [-f/var/log/messages] then echo"/var/log/messages exists. "fi echo "... done. "anny ~> ./Msgcheck. sh This scripts checks the existence of the messages file. Checking.../var/log/messages exists... done.
7.1.1.4. check if the shell option is added 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. "the above example in the fi environment will start to work after the command line is entered: anny ~> If [-o noclobber]; then echo; echo "your files are protected against overwriting."; echo; fi your 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> fi That was a good job! Anny ~> The following example demonstrates that TEST-COMMANDS can be any UNIX command with a return and exit status. if it returns a zero exit status again: anny ~> If! Grep $ USER/etc/passwd More input> then echo "your user account is not managed locally"; fi your user account is not managed locally anny> echo $? 0 anny> The following shows the same result: anny> grep $ USER/etc/passwd anny> if [$? -Ne 0]; then echo "not a local account"; fi not a local account anny>
7.1.2.2. comparison of numbers: anny> num = 'wc-l work.txt 'Anny> echo $ num 201 Anny> If ["$ num"-GT "150"] More input> Then ECHO; echo "you 've worked hard enough for today. "More input> echo; FI you '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. An example of comparing a string to test the user ID:
If ["$ (whoami )"! = 'Root']; then Echo "You have no permission to run $0 as non-root user." Exit 1; FI using Bash, you can shorten the structure.
Below is the simplified structure of the above test: ["$ (whoami )"! = 'Root'] & (echo you are using a non-privileged account; exit 1) is similar to the "&" expression executed if the test is true, "|" indicates 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. "; fi Pleasure to meet you, Madame. anny> most Real Programmers prefer the built-in test commands with the same role as square brackets, like this: test "$ (whoami )"! = 'Root' & (echo you are using a non-privileged account; exit 1) See the information page for more information about Bash "(EXPRESSION )) "and" [[EXPRESSION] "structure. Shell if command parameter description-B returns true if file exists and is a block file-c returns true if file exists and is a character file-d returns true if pathname exists and is a directory true-e: When a file or directory specified by pathname exists, true-f is returned when the file exists and is a regular file.-g: When a file or directory specified by pathname exists and is set if the SGID bit is true,-h is returned when the file exists and is a symbolic link file, this option is invalid in some old systems.-k. When a file or directory specified by pathname exists and a "Sticky" bit is set, true-p is returned when the file exists and is a command pipeline. true-r: if a file or directory specified by pathname exists and is readable, true-s is returned. If the file size is greater than 0, true-u is returned. If a file or directory specified by pathname exists if the SUID bit is set, true is returned. If the file or directory specified by pathname exists and is executable, true is returned. 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.