The basis of each condition statement is to determine what is true or false. Whether or not you understand the working principle of the script will determine whether you are writing a quality script or a script that you will be proud.
The ability of shell scripts is often underestimated, but its ability is actually limited by the ability of script writers. The more you know, the more you will be able to write a file like a magic to automate tasks and simplify your management work.
All operations performed in shell scripts (except the simplest Command Group) must check the conditions. All shell scripts, in a broad sense, can be divided into the following three categories:
If {condition exists} then...
While {condition exists} Do...
Until {condition exists} Do...
No matter what subsequent operations are, these logic-based commands determine whether a condition exists or not to determine subsequent operations. The test command is a utility that allows you to determine the existence of conditions in each case. Therefore, a thorough understanding of this command is essential for successful shell scripts.
Working Principle
The minimum definition of the test command may be to evaluate an expression. If the condition is true, a value of 0 is returned. If the expression is not true, a value greater than 0 is returned, which can also be called a false value. The easiest way to check the status of the last command is to use $? Value. For demonstration purposes, all examples in this article use this parameter.
The test command expects to find a parameter in the command line. When shell does not assign a value to the variable, the variable is treated as null. This means that test reports the error once the parameter found by the script does not exist during script processing.
When trying to protect the script, you can solve this problem by including all parameters in double quotation marks. Shell then expands the variable. If the variable has no value, a null value is passed
Test. Another method is to add an additional check process in the script to determine whether the command line parameters are set. If the command line parameter is not set, the script will tell the user that the parameter is missing and then exit. We
Some examples are used to describe all these content in detail.
Test and [command
Although each version of Linux and UNIX contains the test command, the command has a more common alias-left square brackets :[. Test and Its alias can be found in/usr/bin or/bin (depending on the operating system version and vendor.
When you use left square brackets instead of test, you must always follow a space, a condition to be evaluated, a space, and right square brackets. The right square brackets are not the alias of anything, but the end of the parameter to be evaluated. Spaces on both sides of the condition are required. This indicates that test is called to distinguish it from the character/pattern matching operation that uses square brackets frequently.
The syntax of test and [is as follows:
Test expression
[Expression]
In both cases, test evaluates an expression and returns true or false. If it is used in combination with the if, while, or until command, you can control the Program Stream extensively. However, you do not need to use the test command with any other structure; you can run it directly from the command line to check the status of almost anything.
Because they are aliases of each other, using test or [requires an expression. An expression is generally a comparison of text, numbers, or files and directory attributes, and can contain variables, constants, and operators. Operators can be string operators, integer operators, file operators, or boolean operators-we will introduce each operator in sequence in the following sections.
Test File Operator
Using these operators, you can perform different operations in the program based on the evaluation results of the file type:
-B file: if the file is a special file, it is true.
-C file: if the file is a special character file, it is true.
-D file: if the file is a directory, it is true.
-E file: true if the file exists
-F file: if the file is a normal file, it is true.
-G file: If the sgid bit of the file is set, it is true.
-G file: true if the file exists and belongs to the group
-K file: true if the adhesion bit of the file is set
-O file: true if the file exists and belongs to the user
-P file: if the file is a named pipe, it is true.
-R file: true if the file is readable
-S file: true if the file length is not zero
-S file: if the file is a special socket file, it is true.
-T fd: If FD is an open file descriptor connected to a terminal (FD is 1 by default), it is true.
-U file: If the SUID bit of the file is set, it is true.
-W file: true if the file is writable
-X file: true if the file is executable
The following example shows the running status of this simple operation:
$ LS-l
Total 33
Drwxr-XR-W 2 root Root 1024 Dec 5 05:05 lst
-RW-1 Emmett users 27360 Feb 6 Evan
-Rwsrwsrwx 1 Root 152 Feb 6 hanhannah
Drwxr-XR-x 2 Emmett users 1024 Feb 6 Karen
-RW ------- 1 Emmett users 152 Feb 6 Kristin
-RW-r -- 1 Emmett users 152 Feb 6 Spencer
$
$ Test-r Evan
$ Echo $?
0
$ Test-r Walter
$ Echo $?
1
$
Because the first evaluation is true-the object exists and the readable-return value is true, or 0. Because the file for the second evaluation does not exist, the value is false and the return value is not zero. It is important to specify the value to zero or non-zero, because 1 is not always returned in the case of failure (although this is usually returned), a non-zero value may be returned.
As mentioned at the beginning, in addition to using test, you can also use square brackets [] to enclose the command to issue the same command to shell-as shown below:
$ [-W Evan]
$ Echo $?
0
$ [-X Evan]
$ Echo $?
1
$
Similarly, the first expression is true, and the second expression is false-as indicated by the return value. You can also use the following command to compare the two files:
File1-Ef file2 test to determine whether two files are connected to the same device and whether they have the same inode number
File1-nt file2 test to determine whether the first file is updated later than the second file (determined by the modification date)
File1-ot file2 test to determine if the first file is older than the second file
The following example shows how to use these operators to compare files:
$ [Evan-nt Spencer]
$ Echo $?
0
$ [Karen-ot Spencer]
$ Echo $?
1
$
Files named Evan are updated than files named Spencer and therefore evaluated as true. Similarly, a file named Karen is updated than a file named Spencer, so this evaluation is false.
String comparison operator
As shown in the title, this set of functions compares the value of a string. You can check whether they exist, are the same, or are different.
String test to determine whether the string is not empty
-N string test to determine whether the string is not null. The string must be recognized by test.
-Z string test to determine whether the string is null. The string must be recognized by test.
String1 = string2 test to determine if string1 is the same as string2
String1! = String2 test to determine if string1 is different from string2
One of the most useful tests for any variable is to judge whether its value is not empty. You can simply put it in the test command line to execute this test, as shown in the following example:
$ Test "$ variable"
We strongly recommend that you use double quotation marks to enclose variables for shell to identify variables (even if the variables are empty ). By default, the basic string evaluation and the-n test are functionally the same, as shown in the following example:
# Example1
If test-n "$1"
Then
Echo "$1"
Fi
Execute the code in the above example and give the following results based on whether $1 exists:
$ Example1 Friday
Friday
$
$ Example1
$
If you change the code to the following format, the results will be the same:
# Example2
If test "$1"
Then
Echo "$1"
Fi
As follows:
$ Example2 Friday
Friday
$
$ Example2
$
All of these indicate that-N is usually not required, which indicates the default operation.
To view the possibilities from a different perspective, you can replace-N with another option and check whether the value is null (relative to a non-empty value ). This can be implemented using the-Z option. The code is:
# Example3
If test-z "$1"
Then
Echo "no values were specified"
Fi
Run the following command:
$ Example3
No values were specified
$ Example3 Friday
$
If the program is run without a command line parameter and the expression is evaluated as true, the text in the execution block is used. If a value exists in the command line, the script exits and does not perform any operations. It is very useful to place the evaluation operation at the beginning of the script, which can check the variable value in advance before any further error may occur.
Other string operators evaluate exact matching or difference between two variables/strings (you can also call it "equivalence" or "non-equivalence. The first example tests matching:
$ ENV
LOGNAME = Emmett
Pager = less
Shell =/bin/bash
Term = Linux
$
$ ["$ LOGNAME" = "Emmett"]
$ Echo $?
0
$
$ ["$ LOGNAME" = "Kristin"]
$ Echo $?
1
$
Alternatively, the evaluation can be used as a script to determine whether to run the script:
# Example4
If ["$ LOGNAME" = "Emmett"]
Then
Echo "processing beginning"
Else
Echo "incorrect user"
Fi
This method can be used to find any value (such as the terminal type or shell type). These values must match before the script is allowed to run. Note that, = or! =
The operator has a higher priority than most other options that can be specified and must be accompanied by an expression. Therefore, in addition to the options for comparing strings, = or! =
It cannot be used together with the option to check the existence of something (such as a readable file, executable file, or directory.
Integer comparison operator
Just as string comparison operators verify that strings are equal or different, integer comparison operators perform the same function on numbers. If the value of the variable matches, the expression test is true. If the variable does not match, the expression test is false. The integer comparison operator does not process strings (just as the string operator does not process numbers ):
Int1-EQ int2 if int1 is equal to int2, true
Int1-ge int2 if int1 is greater than or equal to int2, true
Int1-GT int2 if int1 is greater than int2, true
Int1-Le int2 if int1 is smaller than or equal to int2, true
Int1-lt int2 if int1 is smaller than int2, true
Int1-ne int2 if int1 is not equal to int2, true
The following example shows a code segment where the value given in the command line must be 7:
# Example5
If [$1-EQ 7]
Then
Echo "you 've entered the magic number ."
Else
Echo "you 've entered the wrong number ."
Fi
Running:
$ Example5 6
You 've entered the wrong number.
$
$ Example5 7
You 've entered the magic number.
$
Like a string, the value to be compared can be the value assigned to the variable outside the script, rather than always provided in the command line. The following example demonstrates a method to achieve this:
# Example6
If [$1-GT $ number]
Then
Echo "sorry, but $1 is too high ."
Else
Echo "$1 will work ."
Fi
$ Set number = 7
$ Export number
$ Example6 8
Sorry, but 8 is too high.
$ Example6 7
7 will work.
$
One of the best uses of integer comparison operators is to evaluate the number of specified command line variables and determine whether they meet the required standards. For example, if a specific command can only run with three or fewer variables,
# Example7-display variables, up to three
If ["$ #"-GT 3]
Then
Echo "you have given too variable variables ."
Exit $ #
Fi
If three or fewer variables are specified, the script in this example runs normally (and returns 0 ). If more than three variables are specified, an error message is displayed, and the routine exits-the exit code is returned, which is equal to the number of variables specified in the command line.
This process can be modified to determine whether the current day is the last day of the month before the report can be run:
# Example8-to see if it is near the end of the month #
Set 'date' # use backward quotes
If ["$3"-ge 21]
Then
Echo "it is close enough to the end of the month to proceed"
Else
Echo "this report cannot be run until after the 21st of the Month"
Exit $3
Fi
In this example, six variables are set (separated by spaces ):
$1 = Fri
$2 = Feb
$3 = 6
$4 = 08:56:30
$5 = est
$6 = 2004
These values can be used in the script, just as they are entered in the command line. Note that the exit command returns a value again-in this case, the returned value is the date obtained from the value of $3. This technique is useful in troubleshooting.-If you think the script should be running but not, check $? .
A similar idea may be to write a script that runs only on the third Wednesday of every month. The third Wednesday must be between the 15th and 21st of the month. Use
Cron, you can call the script to run at a specified time every day between the 15th to 21st, and then use the first line of the script to check whether the value of $1 (after the date is set) is
Thu. If it is Thu, execute the remaining script. If not, exit.
Another idea is that the script can only run after p.m. () and all users go home. You only need to write the script so that it exits when the value is lower than 18 and get the time by using the following command (set it to $1)
Set 'date + % H'
Boolean operator
Boolean operators work the same way in almost every language-including shell scripts. In nutshell, they check whether multiple conditions are true or false, or take actions on false conditions rather than true conditions. The operators used with test are:
! Expr is true if expression evaluation is false
Expr1-A expr2: true if expr1 and expr2 are evaluated as true
Expr1-O expr2 true if expr1 or expr2 evaluation is true
Yes! = Operator = is used to evaluate the string. This is one of the simplest boolean operators and is not used for normal test results.
The first of the other two operators is the-A (and) operator. To make the test final true, both expressions must be evaluated as true. If any evaluation is false, the entire test is evaluated as false. For example,
$ ENV
Home =/
LOGNAME = Emmett
Mail =/usr/mail/Emmett
Path =:/bin:/usr/lbin
Term = Linux
TZ = est5: 0edt
$
$ ["$ LOGNAME" = "Emmett"-a "$ term" = "Linux"]
$ Echo $?
0
$
$ ["LOGNAME" = "Karen"-a "$ term" = "Linux"]
$ Echo $?
1
$
In the first evaluation, both conditions are tested to be true (emmett is logged on to a Linux terminal), so the entire evaluation is true. In the second evaluation, the terminal check is correct but the user is incorrect, so the overall evaluation is false.
In short, the and operator ensures that the code is executed only when both conditions are met. Conversely, the OR (-O) operator is true if any expression is tested to be true. Let's modify the previous example and put it in a script to illustrate this:
# Example9
If ["$ LOGNAME" = "Emmett"-o "$ term" = "Linux"]
Then
Echo "ready to begin ."
Else
Echo "incorrect user and terminal ."
Fi
$ ENV
Home =/
LOGNAME = Emmett
Mail =/usr/mail/Emmett
Path =:/bin:/usr/lbin
Term = Linux
TZ = est5: 0edt
$ Example9
Ready to begin.
$
$ LOGNAME = Karen
$ Example9
Ready to begin.
$
When the script is run for the first time, it evaluates whether the user is equal to Emmett. If the user is found to be equal to Emmett, the script goes to echo
Statement, and skip other checks. It never checks whether the terminal is equal to or not
Linux, because it only needs to find a true statement to make the entire operation true. When the script runs for the second time, it determines that the user is not Emmett, so it will check and find that the terminal is indeed
Linux. Because one condition is true, the script now goes to the echo command. To extract the second message, both conditions must be false.
In the previous example of determining whether the time is the end of the month, you can perform a similar check to prevent the user from trying to run the script on the weekend:
# Example10-do not let the script run over the weekend #
Set 'date' # use backward quotes
If ["$1" = "sat"-o "$1" = "sun"]
Then
Echo "this report cannot be run over the weekend ."
Fi
Some useful examples
Example 1: the simplest form of "logic" in the script file (as shown in all examples in this article) is "if...
Then statement. In the previous code segment, check whether there are a certain number of variables and then echo these variables. Suppose we make some changes to this, for example, we want to echo the variable, and each ECHO is reduced
The leftmost variable to show an inverted triangle.
Although this sounds simple, it is not actually the case; this is the way you want to implement large-scale processing: process the first variable, transfer, process the next variable ......
For demonstration purposes, you can write important lines in the script as follows:
# Example11-display declining variables, up to three
If ["$ #"-GT 3] # See if more than three variables are given
Then
Echo "you have given more than three variables ."
Exit
Fi
Echo $ *
If test-n "$2"
Then
Shift
Echo $ *
Fi
If test-n "$2"
Then
Shift
Echo $ *
Fi
It will be executed as follows:
$ Example11 one
One
$
$ Example11 one two
One Two
Two
$
$ Example11 one two three
One two three
Two Three
Three
$
$ Example11 one two three four
You have given more than three variables.
$
The reason for limiting the number to three variables for the purpose of checking is to reduce the number of rows to be checked in the example. Everything goes on step by step, though it's incredibly confusing; the user gets a warning over the number of variables the program can handle based on the design, and the script exits. If the number of variables is 3 or less, the core part of the operation starts to be executed.
Echo the variable and run the test to check whether another variable exists. If another variable exists, perform a transfer, echo the variable, and perform another test. A total of 16
Valid rows, and the program can only process up to three variables-
Very messy. If the limit on the number of variables is eliminated, the program can process any number of variables. After some modifications, the script is shortened (beautified) and can process any number of variables:
# Example12-display declining variables, any number
While ["$ #"-GT 0]
Do
Echo $ *
Shift
Done
$ Example12 1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
2 3 4 5 6 7 8 9 0
3 4 5 6 7 8 9 0
4 5 6 7 8 9 0
5 6 7 8 9 0
6 7 8 9 0
7 8 9 0
8 9 0
9 0
0
The number of valid rows is reduced to only five, and the restriction of the three variables in the first script is eliminated, and it is more efficient at runtime.
Example 2: Whenever a processing-related operation is executed in the script, the next operation will always check the status of the previous operation to confirm that it has been completed successfully. You can check $? And verify that it is equal to 0. For example, if a data directory can be accessed,
# Example13
Temp = lst
CD $ temp
If [$? -Ne 0]
Then
Echo "data directory cocould not be found ."
Exit
Fi
Handling error
Resources
Download the Oracle Database 10 Gb for Linux
Oracle Database 10g 1st (10.1.0.2) is now available for Linux x86 and Linux itanium platforms. Please download it from OTN for free.
Access the Linux Technical Center
Add this page to your favorites to obtain general technical information about the best application of the Linux system administrator and detailed technical information about the Oracle-on-Linux product group.
Related Articles
Archiving of Linux-related technical articles
The test command usually has two types of errors. The first is that the correct evaluation type is not used. For example, you can compare a string variable with an integer variable or a string with or without filling. A careful evaluation of the variables you use will allow you to ultimately find the root cause of the error and allow you to solve these problems.
The second type of error is to mistake square brackets for something other than an alias. There must be a space between square brackets and their content; otherwise, they cannot interpret the objects. For example,
$ ["$ LOGNAME"-GT 9]
Test:] Missing
$
Note that the error message indicates a problem with test, even if an alias is used]. These problems are easy to find, because the error message accurately displays these problems, and you can add necessary spaces.
Conclusion
To build logic in shell scripts, you must add conditional statements. The core of each such statement is to evaluate the condition to determine whether it exists-use the test command to complete the evaluation. Understanding how it and its alias (left square brackets ([) work will enable you to write shell scripts that can complete some complex operations.