Conditional testing of shell learning

Conditional test

The command test or can test whether a condition is true. If the test result is true, the Exit Status of the command is 0. If the test result is false, the Exit Status of the command is 1 (note that it is just the opposite of the logical representation of the C language) . For example, to test the magnitude relationship of two numbers:

itcast@ubuntu:~$ var=2

itcast@ubuntu:~$ test $var -gt 1

itcast@ubuntu:~$ echo $?

0

itcast@ubuntu:~$ test $var -gt 3

itcast@ubuntu:~$ echo $?

1

itcast@ubuntu:~$ [ $var -gt 3 ]

itcast@ubuntu:~$ echo $?

1

itcast@ubuntu:~$

Although it looks strange, the left square bracketis indeed the name of a command, and the parameters passed to the command should be separated by spaces, for example: $VAR , -gt , 3 , ]  is the four parameters of the [  command , they must be separated by spaces. The parameter form of the command test or [  is the same, except that the test command does not require a ]  parameter. Taking the [ command as an example, the common test commands are shown in the following table:

[ -d DIR ] True if DIR exists and is a directory

[ -f FILE ] True if FILE exists and is a regular file

[ -z STRING ] True if STRING has zero length

[ -n STRING ] True if the length of STRING is non-zero

[ STRING1 = STRING2 ] True if the two strings are the same

[ STRING1 != STRING2 ] True if the strings are not identical

[ ARG1 OP ARG2 ] ARG1 and ARG2 should be integers or variables with integer values, OP is -eq(equal)-ne(not equal)-lt(less than)-le(less than or equal)-gt(greater than)-ge (greater or equal to)
one of the

Similar to the C language, and, or, and non-logical operations can also be performed between test conditions:

[ ! EXPR ] EXPR can be any of the test conditions in the above table, ! means "logical inverse (not)"

[ EXPR1 -a EXPR2 ] EXPR1 and EXPR2 can be any of the test conditions in the above table, -a means "logical AND"

[ EXPR1 -o EXPR2 ] EXPR1 and EXPR2 can be any of the test conditions in the above table, -o means "logical or"

E.g:

$ VAR = abc

$ [ -d Desktop -a $VAR = 'abc' ]

$ echo $?

0

Note that if the

If the $VAR variable in the example is not defined in advance , it will be expanded into an empty string by the shell , which will cause a syntax error in the test condition (expanded as [ -d Desktop -a = ' abc ' ] ), which is a good Shell programming practice , the variable value should always be enclosed in double quotes (expands to [ -d Desktop -a "" = ' abc ' ] ):

$ unset VAR

$ [ -d Desktop -a $VAR = 'abc' ]

bash: [: too many arguments

$ [ -d Desktop -a "$VAR" = 'abc' ]

$ echo $?

1

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324599563&siteId=291194637