"Focus" Shell Getting Started Tutorial: Process Control (2) The wording of conditional judgment

Source: Internet
Author: User
Tags readable

Section III: The wording of conditional judgment

If conditional judgment, the "conditional judgment" in the grammatical structure of if can have many forms. The test result is true, just to see if it returns a value of 0.

The following 10 types of conditional tests are available:

1. Execute the result of a command

Here's the command, which can include pipeline commands, for example: command 1 | Command 2 | Command 3, called pipeline, whose end state is the result of the last command execution.

Example:

#!/bin/bashif grep-q "rm" fn.sh; Thenecho "Find in command." Elseecho "not find." Fi

Line 3, in the condition test, when executing the command: Grep-q "rm" fn.sh, which is to find the fn.sh file if there is a keyword RM. Option-Q means no display, only with $? To return the execution results.

2. Returns the opposite value of a command execution result

The form is:! Command

Attention! And the command must be separated by a "space".

If the command returns a value of 0, add it! The return value is 1, and conversely, if the command returns a value other than 0, add it! , the value returned is 0.

Example:

#!/bin/bashif! Grep-q "rm" fn.sh; Thenecho "not find." Elseecho "Find RM command" fi

3. Using the Compound command: ((arithmetic))

If the result of the calculation is not 0, it returns the True value (0), otherwise, if the result of the operation is 0, the false values (1) are returned. Another example is as follows:

((5*6))
(calculation) result determine true or false
((0)) 0 false
((1)) 1 true
((8)) 8 true
(( -1) -1 true
((2-2)) 0 false
true
((20<30)) Numeric comparison operation true true
((20&&30)) Logical AND operation is true true
((20&&0)) Logical AND operation False false
((0&&1)) logical AND Operation false false
((10| | 0) logical OR operation is true true
(0| | 1) logical OR operation is true true
(0| | 0)) logical OR operation is false false

4. Use the BASH keyword ' [[', ']] ' formula: [[judging]]

The interpretation will return the true and False value, return 0 is true, not 0 is false.

Note: [[behind,]] before, at least one (including) more than the "space" line.

Example:

#!/bin/bashif [[str > XYZ]]; Thenecho "string str comparison large" Elseecho "string str relatively small" fi

Execution Result: Display "string str relatively small"

5. Using built-in commands: test-judged

Test is a built-in command of bash, which returns the result of the "judgment" and returns the true value back to 0, which returns 1.

Example:

#!/bin/bashif test "str" \> "XYZ"; Thenecho "string str comparison large" Elseecho "string str relatively small" fi

Execution Result: Display "string str relatively small"

It is important to note that the greater than symbol > is a special character for Bash, which is escaped with \, otherwise the correct test result cannot be obtained.

6. Use the built-in command: []

Format: [Judging]

The usage of [] and test is the same, and the two can be rewritten interchangeably.

Example:

#!/bin/bashif ["str" \> "XYZ"]; Thenecho "string str comparison large" Elseecho "string str relatively small" fi

Execution Result: Display "string str relatively small"

It is important to note that the greater than symbol > is a special character for Bash, which is escaped with \.

The 1th line of this example can be changed to the use of test

if test "str" \> "XYZ"; Then

7. Logic combination using-A,-O:

Note:-A,-O is placed in the [] inside!

Example:

[-R filename1-a-X filename1]

True if the filename1 is readable and executable. -O is the meaning of "and".

[-R Filename1-o-X filename1]

True if the filename1 is readable or executable. -O is the meaning of "or".

8. Command 1 && Command 2

&& is called logical and, and it works by "Command 2" If the result of "command 1" is true, or if two are true, return True value 0, or return false values 1.

#!/bin/basha=20if grep-q "rm" fn.sh && [$a-lt 100]; Thenecho "OK" elseecho "not ok" fi

The characteristics of && are often taken as an invisible if syntax. For example:

[-Z "$PS 1"] && return

The code means: first determine whether the value of the $PS variable is empty, if so, execute the return command, the child shell Environment returned to the parent shell, and so on to end the execution of the script. is equivalent to the following if statement:

If [-Z ' $PS 1 "]; Thenreturn;fi

Let's look at one more example:

[-f/proc/net/if_inet6] && echo ' This host supports IPV6 '

Henceforth, the form of "[Judgment] && instruction" is regarded as an invisible if-then grammar.

9. Command 1 | | Command 2

|| Called logical OR, it works by "Command 2" If the result of "command 1" is false, and if one of the two is true, returns the truth 0, or returns the False value 1.

#!/bin/basha=200if grep-q "rm" fn.sh | | [$a-lt 100]; Thenecho "OK" elseecho "not ok" fi

|| can also be used as an invisible if syntax. For example:

prefix= "/Home" defpath= "/usr/local/bin" [-Z ${prefix:-}] | | prefix=${defpath%/*}

Line 3, because $prefix non-empty, so the return value of ${prefix:-} variable extension is prefix variable value (non-null), [-Z ${prefix:-}] null value of the condition test failed, the result is false, according to | | prefix=${defpath%/*}, it will delete the shortest string of style/* from the $defpath, i.e. delete/bin, so the value of the $prefix is/usr/local.

This example can be changed to the IF syntax as follows:

prefix= "Home" defpath= "/usr/local/bin" if [!-Z ${prefix:-}]; Thenprefix=${defpath%/*}fi

10.&& and | | Share

&& | | can also have if-then-else effect, for example:

[-N ${debug:-}] && Set-v | | Set +v

This line of code, using the-N test variable debug whether there is a non-null value, if any, indicates to be wrong, then execute the next command of and: Set-v; if none, then the next instruction of the logical OR is executed: Set-v, which closes the function of the display program.

This example can overwrite if syntax as follows:

If [-N "$DEBUG"]; Thenset-velseset +vfi

Hereafter, all "[Judgment] && directive 1 | | The form of Instruction 2 "is regarded as an invisible if-then-else grammar."

Final Summary:

In the methods described above, [[]] and test, [] are similar in meaning and usage, but [[]] are more liberal than Test and [] because [[]] do not have to worry about the effects of some bash special characters on the operator, do not write a bunch of escape characters, such as [[Str < XYZ]] is the correct syntax, but in [] is written in [str \< XYZ], this trap is easy to forget, once you forget to write the escape character, to find the error, it is not easy. in [[]],<, >, &&,, | | Can be used freely without the use of escape characters.

In addition to [[]], in bash, there is no need to ignore the effects of the special characters mentioned above.

Below, there is another point to pay special attention to:

In [[judging]] , if you use = = or! =, and the string to the right of the two operators does not add single or double quotes , then = = and! = are considered to be the "style" that you want to compare the string to, and if it is equal, return 0, and if not, return 1.

Example:

#!/bin/basha= "STR" if [[$a = =???]]; Thenecho "Match" fi

Line 4,[[$a = =???]] means that, with $a value, the comparison style ??? (3-character string ).

But if you change the line 4 to:

if [[$a = = "???"]]; Then

The meaning is different, at this time = = to be judged $a and string??? are equal.

"Focus" Shell Getting Started Tutorial: Process Control (2) The wording of conditional judgment

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.