Conditional judgment in Bourne shell

Source: Internet
Author: User
Tags arithmetic

Conditional judgment is the basis for a program to gain intelligence, while the Bourne shell script simulates conditional expressions in most programming languages by command.

The control structures supported in the shell are:

(1) If then else fi

(2) for on Do

(3) while doing done

The second is primarily used for traversal, which may not require conditional judgment, and the other two types are unavoidable and [commands are used together. The following explains how this command simulates conditional expressions.

File/directory judgment
[-B file] True if file exists and is a block special file.
[-C file] True if file exists and is a word special.
[-D DIR] true if FILE exists and is a directory.
[-E File] True if file exists.
[-F file] True if file exists and is a normal file.
[-G file] True if file exists and Sgid has been set.
[-K file] True if file exists and the sticky bit has been set.
[-P file] If file exists and is a name pipe (f if O) is true.
[-R File] True if file exists and is readable.
[-S file] True if file exists and the size is not 0.
[-T FD] true if the file descriptor FD is open and points to a terminal.
[-u file] True if file exists and suid (set user ID) is set.
[-W file] True if file exists and is writable.
[-X file] True if file exists and is executable.
[-o file] True if file exists and is a valid user ID.
[-G file] True if file exists and is a valid user group.
[-L file] True if file exists and is a symbolic connection.
[-N file] If file exists and has been mod if IED since it is last read is true.
[-S file] True if file exists and is a socket.
[File1-nt FILE2] If FILE1 have been changed more recently than FILE2, or if FILE1 exists and FILE2 does not is true.
[File1-ot FILE2] If FILE1 is older than FILE2, or FILE2 exists and FILE1 does not exist, it is true.
[File1-ef FILE2] True if FILE1 and FILE2 point to the same device and node number.

String judgments
[-Z string] True if the length of the string is zero, that is, if it is NULL, then NULL is true;
[-N string] True if the length of the string is nonzero, that is, the non-null is true;
[STRING1 = STRING2] True if two strings are the same;
[STRING1! = STRING2] True if the string is not the same;
[STRING1] True if the string is not empty, similar to-n

Numerical judgment
Int1-eq INT2 INT1 and INT2 two numbers equal to true, =
Int1-ne INT2 INT1 and INT2 two numbers are true,<>
INT1-GT INT2 INT1 greater than INT1 for true,>
Int1-ge INT2 INT1 greater than or equal to INT2 true, >=
Int1-lt INT2 INT1 less than INT2 for true,<
Int1-le INT2 INT1 less than equals INT2 true, <=

In summary , "=" is used to compare strings; "-eq" is used to compare integers

Complex logic judgment
-A and
-O or
! Non -

1, if A>b and A<c
if ((a > B)) && ((a < C))
if [[$a > $b] && [[$a < $c]]
If [$a-gt $b-a $a-lt $c]

2. If A>b or a<c
if ((a > B)) | | ((a < C))
if [[$a > $b] | | [$a < $c]
If [$a-gt $b-o $a-lt $c]

"||" and "&&" can be used in the shell, the first one can be written if [A>b && a]

The meanings of the brackets and the double brackets are explained in the following paragraphs for the various parentheses.

Parentheses in the shell (), (()), [], [[]]

1, single parenthesis ()
① Command Group. The commands in parentheses will be executed in a new sub-shell sequence, so the variables in parentheses cannot be used by the rest of the script. Multiple commands in parentheses are separated by semicolons, and the last command can have no semicolon, and there is no space between the commands and the parentheses.
The ② command is replaced. Equivalent to ' cmd ', the shell scans the command line once, discovers the $ (CMD) structure, executes the cmd in $ (cmd) once, obtains its standard output, and then places the output in the original command.
The ③ is used to initialize the array. such as: Array= (a b c d)

2. Double parenthesis (())
① integer extension. This extended calculation is an integer-type calculation and does not support floating-point types. (exp) structure expands and computes the value of an arithmetic expression, if the result of the expression is 0, the exit status code returned is 1, or false, and a non-0-valued expression returns an exit status code of 0, or true.
② can be used in $ (exp), as long as the operators and expressions in parentheses conform to the C-language arithmetic rules. For different carry (such as binary, octal, hex) operations, the output is automatically converted to decimal. such as: Echo $ ((16#5f)) result is 95 (16 decimal). The values of variables such as a=5 can also be redefined by simply using (()). ((a++)) to redefine $a to 6. Variables in double brackets can not use the $ symbol prefix. Multiple expressions are supported in parentheses, separated by commas.
③ can even replace the looping structure, as long as the expression in parentheses conforms to the C-language arithmetic rules. For example, you can directly use for ((i=0;i<5;i++)), if you do not use double brackets, then for i in ' seq 0 4 ' or for I in {0..4}. If you can use the IF (($i <5)) directly, if you do not use double brackets, then if [$i-lt 5].

3. Single brackets []
The ① standard command [and test are the same, except that the last parameter of the command is "]".
② is used in regular expressions to represent a range of characters. The regular is not used within brackets as a test purpose.
④ in the context of an array structure, brackets are used to refer to the number of each element in the array.

4. Double brackets [[]]
①[[is a key word for the Bash programming language and is not a command. [[]] structure is more general than [] structure, but note [[still] and the contents inside the brackets are separated by a space.
② supports pattern matching of strings, supports regular expressions when using the =~ operator, supports wildcard characters when using the = = operator, and can use the right side as a pattern instead of just a string, such as [[Hello = = Hell]], and the result is true.
③ using [[...]] The conditional judgment structure, rather than [...], can prevent many logic errors in the script. For example, the,&&, | |, <, and > operators can normally exist in the [[]] conditional judgment structure, but if they appear in the [] structure, the error occurs because the [command does not explain the meaning of &&. For example, you can use if [[$a! = 1 && $a! = 2]], if you use a single parenthesis, if [$a-ne 1] && [$a! = 2] or if [$a-ne 1-a $a! = 2].
④bash the expression in double brackets as a separate element and returns an exit status code.

Other about the shell

The shell sometimes relies on commands to simulate operations. For example, arithmetic can be completed with commands such as Let, expr, and so on. If the variable x plus 1 can be written: let "x = $x + 1" or x= ' expr $x + 1 '. If the arguments have spaces , be sure to enclose them in quotation marks. Whitespace is meaningful in the shell.

PS: Note that all the input in the shell is a string type (of course, any language is the same, but the shell supports less type interpretation and conversion), where the dollar symbol $ anti-quote ' backslash \ is interpreted as a string substitution or command substitution by the SH process or bash process. That is, replace the original command with a specific output string before continuing with the new command.

Debugging:

To view the execution of a shell script
At the time of execution, in the following way:
#sh-X test.sh

Get Parameters:

$# is the number of arguments passed to the script
The name of the script itself
$ $ is the first parameter passed to the shell script
$ $ is the second parameter passed to the shell script
[Email protected] is a list of all parameters passed to the script
$* is to display all parameters passed to the script in a single string, with more than 9 parameters, unlike positional variables
$$ is the current process ID number for the script to run
$? is to display the exit status of the last command, 0 means no error, others indicate an error

Conditional judgment in Bourne shell

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.