Linux test command

Source: Internet
Author: User
Tags echo command

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.

Shell

Script capabilities are often underestimated, but in fact their capabilities are 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
.

All operations performed in shell scripts (except the simplest Command Group) must check the conditions. All shell scripts "logic "-
In a broad sense, "logic" can generally be divided into the following three categories:

If {condition exists} then...
While
{Condition exists} Do...
Until {condition exists} Do...

Regardless
What are subsequent operations? These logic-based commands depend on determining whether a condition actually exists to determine subsequent operations. Test
A command is a utility that allows you to determine whether a condition exists in each case. Therefore, a thorough understanding of this command is essential for successful shell scripts.

Work
Operating 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.
-It 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.

Test
The command expects to find a parameter in the command line. If the shell does not assign a value to the variable, the variable is treated as null. This means that when processing the script, once the parameter found by the script does not exist
Test reports this error.

When trying to protect the script, you can solve this problem by including all parameters in double quotation marks. Then Shell
Expand 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 Linux and UNIX
Each version contains the test command, but this command has a more common alias-left square brackets :[. Test and Its alias can be stored in/usr/bin or/bin
(Depending on the operating system version and vendor.

When you use left square brackets instead of test
Always followed by 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 you need to call test 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 and
If, while, or until commands are used in combination, you can control the Program Stream extensively. However, you do not need
The command is used 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, use test or [
An expression is required. 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, and file operators.
Or boolean operator-we will introduce each operator in sequence in the following sections.

Test File Operator

Using these operators, you can
Perform different operations on the file type evaluation results:

-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 object 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 the 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 file exists and is readable-
The 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 it will not always return
1 (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 []
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

To
The following example shows how to use these operators to compare files:

$ [Evan-nt Spencer]
$ Echo $?
0
$
[Karen-ot Spencer]
$ Echo $?
1
$

A file named Evan is named
Spencer's file updates, so the evaluation is true. Similarly, a file named Karen is updated than a file named Spencer, so this evaluation is false.

Word
Character 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 whether string1 matches
Same as string2
String1! = String2 test to determine if string1 is different from string2

For any
One of the most useful tests of a 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 this test to allow Shell
Identifies a variable (even if the variable is 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

Run the code in the above example according to $1
Whether the following results exist:

$ Example1 Friday
Friday
$
$ Example1
$

For example
If you change the code to the following format, the result 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
You can use another option to replace-N 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

Operation
The rows are as follows:

$ 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 there is a value in the command line,
The script exits without any operation. 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 operations
Operator evaluates the 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 can 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 the string comparison operator
If the certificate string is equal or different, the integer comparison operator performs the same function on the number. 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 (positive
If 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: true if int1 is smaller than or equal to int2
Int1-lt int2 if int1 is smaller than int2, true
Int1
-Ne int2: true if int1 is not equal to int2

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 in the command
. 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 specified commands.
The number of rows, and determine whether it meets 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 implements variables ."
Exit $ #
Fi

Specify three or fewer variables.
The sample script 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.

Pair
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
Month to proceed"
Else
Echo "this report cannot be run
After the 21st of the Month"
Exit $3
Fi

In this example, six variables are set (
Cells are separated from each other ):

$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. Please 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 possible idea is to allow only scripts at p.m.
(), All users go home and run. 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
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 is evaluated as true

Yes! = Operator substitution =
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-a (that is
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
In the first evaluation, both conditions are tested to be true.
Emmett), so the overall 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, and
The operator ensures that the code is executed only when both conditions are met. Conversely, as long as any expression test is true, or (-O)
The operator is 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
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.

Example of whether the previous time is the end of the month
Child, 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 it when performing large-scale processing: to process the first variable,
Transfer and 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 sets
Run the following command:

$ 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 in the example.
The number of rows to check. 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 and echo the variable,
Execute another test, and so on. A total of 16 valid rows are used, 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

Now reduced to only 5
It eliminates the restrictions on the three variables of the first script and 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
To achieve this goal. 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

Location
Handling error

Resources

Download the Oracle Database 10 Gb for Linux
Oracle Database 10g 1st
(10.1.0.2) currently available for Linux x86 and Linux itanium platforms; download from OTN for free here.

Access
Linux Technical Center
Add this page to your favorites to get general technical information about the best application of Linux system administrators and about Oracle-on-Linux
The specific technical information of the product group.

Related Articles

Archiving of Linux-related technical articles

Test
There are actually only two types of errors that often occur in a command. The first is that the correct evaluation type is not used. For example, you can compare a string variable with an integer variable or use a string with or without filling.
Comparison. 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
$

Please note that the error message indicates that there is a problem with test, even if the 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 go to the shell
To build the logic in the script, you must add a conditional statement. The core of each such statement is to evaluate the condition to determine whether it exists-by using 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.

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.