Original address: http://blog.chinaunix.net/uid-24607609-id-2118151.html
The syntax for the most streamlined
if command is:
if TEST-COMMANDS; then CONSEQUENT-COMMANDS; fi
after the
Test-command executes and its return status is 0, the
consequent-commands executes. The return status is the exit state of the last command, or 0 if no condition is true.
Test-command often includes comparison tests of numbers and strings, but it can also be any command that returns status 0 on success or returns some other state when it fails. Unary expressions are often used to check the state of a file. If a feature is primaries, the
FILE
parameter is
/dev/fd/N
in this form, then the file descriptor "N" is checked.
stdin
,
stdout
and
stderr
their respective file descriptors can also be used for testing. 7.1.1.1. And if expressions are usedThe following table contains an overview of what constitutes a
test-command command or a list of commands, called feature primaries. These primaries are placed in square brackets to represent a test of a conditional expression.
Table 7.1. Main expression
Primary |
meaning |
[ -a FILE ] |
FILE true if it exists. |
[ -b FILE ] |
True if it FILE exists and is a block special file. |
[ -c FILE ] |
FILE true if a special file is present and is a word. |
[ -d FILE ] |
True if it FILE exists and is a directory. |
[ -e FILE ] |
FILE true if it exists. |
[ -f FILE ] |
True if it FILE exists and is an ordinary file. |
[ -g FILE ] |
FILE true if Sgid is present and has been set. |
[ -h FILE ] |
True if it FILE exists and is a symbolic connection. |
[ -k FILE ] |
True if the FILE sticky bit is present and has been set. |
[ -p FILE ] |
True if it FILE exists and is a name pipe (f if o). |
[ -r FILE ] |
True if it FILE exists and is readable. |
[ -s FILE ] |
FILE true if it exists and the size is not 0. |
[ -t FD ] |
True if the file descriptor is FD open and points to a terminal. |
[ -u FILE ] |
True if the FILE suid (set user ID) is present and set. |
[ -w FILE ] |
FILE true if FILE exists and is writable. |
[ -x FILE ] |
True if it FILE exists and is executable. |
[ -O FILE ] |
FILE true if it exists and is a valid user ID. |
[ -G FILE ] |
FILE true if it exists and is a valid user group. |
[ -L FILE ] |
True if it FILE exists and is a symbolic connection. |
[ -N FILE ] |
If FILE an and has been mod is present, if the IED since it is last read is true. |
[ -S FILE ] |
True if it FILE exists and is a socket. |
[ FILE1 -nt FILE2 ] |
if have FILE1 been changed more recently than FILE2 , or if FILE1 FILE2 does not is true. exists and |
[ FILE1 -ot FILE2 ] |
True if it is FILE1 older than it is FILE2 , or FILE2 exists and FILE1 does not exist. |
[ FILE1 -ef FILE2 ] |
FILE1 true if and FILE2 point to the same device and node number. |
[ -o Optionname] |
True if the shell option "Optionname" is turned on. |
[ -z STRING] |
"STRING" is true if the length is zero. |
[ -n String] or [string] |
The length of "STRING" is not 0 Non-zero is true. |
[STRING1 = = STRING2] |
If 2 strings are the same. "=" May is used instead of "= =" for strict POSIX compliance is true. |
[STRING1! = STRING2] |
True if the strings are not equal. |
[STRING1 < STRING2] |
If the "STRING1" sorts before "STRING2" lexicographically the current locale is true. |
[STRING1 > STRING2] |
If the "STRING1" sorts after "STRING2" lexicographically the current locale is true. |
[ARG1 OP ARG2] |
"OP" is one -eq of,,, -ne -lt -le , -gt or -ge . These arithmetic binary operators return true if "ARG1" is equal to, not equal to, less than, less than or equal to, great Er than, or greater than or equal to "ARG2", respectively. "ARG1" and "ARG2" are integers. |
expressions can be combined with the following operators to reduce the sequence: listed in decreasing order of precedence:
table 7.2. Combining Expressions
Operation |
Effect |
[! Expr] |
EXPR false is true. |
[(EXPR)] |
< Span style= "font-size:large;" > Returns the value of EXPR . This can be used to ignore the normal operator precedence. |
[expr1-a EXPR2] |
if EXPR1 and EXPR2 The whole truth is true. |
[expr1-o EXPR2] |
if EXPR1 or EXPR2 To be true is to be true. |
the
[ (or
test) built-in command evaluates a conditional expression using a series of rules based on the number of parameters. More information on this topic can be found in the bash documentation. Just like
if you end up using
fi , you have to end up with ">" After the condition is finished. 7.1.1.2. Commands for subsequent then statements
consequent-commands lists the following then
statements can be any valid UNIX command, any executable program, any executable shell script, or any shell statement, except
Fi. 。 It is important
to remember that then and
fi are considered separate statements inside the shell. Therefore, when used on the command line, they are separated by semicolons. in a script, the different parts of an if statement are usually well delimited. Here are some simple examples:7.1.1.3. Checking FilesThe first example checks for the existence of a file:
anny ~>
msgcheck.sh
#!/bin/bash
echo "This scripts checks the existence of the messages file."
echo "Checking ..."
if [-f/var/log/messages]
Then
echo "/var/log/messages exists."
Fi
Echo
echo "... done."
anny ~>
./msgcheck.sh
This scripts checks the existence of the messages file.
Checking ...
/var/log/messages exists.
... done.
7.1.1.4. Check shell OptionsAdd to your bash configuration file:
# These lines would print a message if the Noclobber option is set:
If [-O noclobber]
Then
echo "Your files are protected against accidental overwriting using redirection."
Fi
|
Environment |
The above example will start working after the command line is entered:anny ~> [ -o noclobber ] "your files are protected against overwriting." ; echo; Fi
Your files are protected against overwriting.
anny ~> However, if you use an environment-dependent test, when you enter the same command in the script you may get no results, because the script opens a new shell that does not set the expected variables and options. |
7.1.2. Simple application of If7.1.2.1. Test exit statusThe
?
variable contains the exit status of the previously executed command (the most recently completed foreground process). The following example shows a simple test:
anny ~>
[ $? -eq 0 ]
More input>
‘That was a good job!‘
More input>
Fi
That is a good job!
anny ~>
The following example proves that
test-commands can be any Unix command that has a return and exit status, and then
if it returns a zero exit state again:
anny ~>
! grep $USER
/etc/passwd
More input>
"your user account is not managed locally"
; Fi
Your user account was not managed locally
anny >
$?
0
anny >
The same results can be obtained from the following:
anny >
$USER
/etc/passwd
anny >
[ $? -ne 0 ]
"not a local account"
; Fi
Not a local account
anny >
7.1.2.2. Comparison of NumbersThe following example uses a numerical comparison:
anny >
num
=`wc -l work.txt`
anny >
$num
201
anny >
[ "$num" -gt "150" ]
More input>
"you‘ve worked hard enough for today."
More input>
echo; Fi
You ' ve worked hard enough for today.
anny >
This script is executed every Sunday by Cron. If the number of weeks is even, he reminds you to clean the Trash box:
#!/bin/bash
# Calculate the week number using the date command:
weekoffset=$[$ (date + "%V")% 2]
# Test If we have a remainder. If not, the is a even week so send a message.
# Else, do nothing.
If [$WEEKOFFSET-eq "0"]; Then
echo "Sunday evening, put out the garbage cans." | Mail-s "garbage cans out" [Email protected]_domain.org
7.1.2.3. String ComparisonsAn example of testing a user ID by comparing strings:
If ["$ (whoami)"! = ' root ']; Then
echo "You had no permission to run $ as Non-root user."
Exit 1;
Fi
with bash, you can shorten such a structure. Here is the streamlined structure for the above tests:
["$ (whoami)"! = ' root '] && (echo you is using a non-privileged account; Exit 1)
similar to the "&&" expression that is executed if the test is true, "| |" Specifies that the test is false on execution. An expression similar to "&&" indicates the action taken when two test conditions are true, "| |" indicates the actions taken when the test is false. Regular expressions can also be used in comparisons:
anny >
gender
="female"
anny >
[[ "$gender" == f* ]]
More input>
"Pleasure to meet you, Madame."
; Fi
Pleasure to meet you, Madame.
anny >
|
A real programmer |
Most programmers prefer to use built-in test commands that have the same effect as square brackets, like this:Test "$ (whoami)"! = ' root ' && (echo you is using a non-privileged account; Exit 1)
|
See the information page for more information about module matching for bash (expression) and [[expression]] structures.
Shell if command parameter description
-B Returns True when file exists and is a block file
-C Returns True when file exists and is a character
-D returns True when pathname exists and is a directory
-E Returns True when a file or directory specified by pathname is present
-F Returns True when file exists and is regular
-G returns True when the file or directory specified by pathname is present and the Sgid bit is set
-H Returns True when file exists and is a symbolic link file, this option is not valid on some old systems
-K returns True when a file or directory specified by pathname exists and the "sticky" bit is set
-P Returns True when file exists and is a command pipeline
-R Returns True when the file or directory specified by pathname is present and readable
-s when file size is larger than 0 o'clock returns true
-U returns True when the file or directory specified by pathname is present and the SUID bit is set
-W Returns True when the file or directory specified by pathname exists and is executable. A directory must be executable for its content to be accessed.
-O Returns True when the file or directory specified by pathname is present and is owned by the user specified by the active user ID of the current process.
Compare character notation:
-eq equals
-ne Not equal to
-GT Greater than
-lt less than
-le less than or equal to
-ge greater than or equal to
-Z Empty string
* = Two characters equal
*! = Two characters Range
*-N Non-empty string
How to use the Linux shell if statement