The IF condition of the Linux shell script is judged

Source: Internet
Author: User

If condition judgment

1. Basic syntax:
if [command]; Then
Statements that meet the criteria for execution
Fi


2. Extended syntax:
if [command];then
Statements that meet the criteria for execution
elif [Command];then
Statements that meet the criteria for execution
Else
Statements that meet the criteria for execution
Fi

3. Syntax Description:
The bash Shell executes the IF statement sequentially, and if the command executes and its return status is 0, the statement that conforms to that condition executes will be executed, otherwise the subsequent commands do not execute and skip to the next command.
When there is more than one nesting, only the first command that returns a 0 exit state causes the part of the statement that conforms to that condition to execute, and if all statements do not have a state of 0, then the Else statement is executed.
Return Status: The exit state of the last command, or 0 if no condition is true.


Note:
1, [] indicates the condition test. Note that the space here is important. Be aware that there must be spaces before ' [' and '] '
2. In the shell, then and FI are separate statements. If you want to enter in the same line, you need to separate them with semicolons.
3, note that if the processing of variables in the judgment, need to quote, in order to avoid some unnecessary errors. No double quotes produce errors when judged by string variables, including spaces. For example [-N "$var"] if Var is empty error
4, the judgment is not support floating-point value
5, if only use > or < alone, the system will be considered as output or input redirection, although the results are correct, but in fact, it is wrong, so you want to change these symbols
6. In the default, the error message generated by running the command in the IF statement still appears in the output of the script
7, when using-Z or-N to check the length, there is no defined variable is also 0
8. Null variables and uninitialized variables can have a disastrous effect on shell script testing, so when you're unsure of the contents of a variable, use-N or-Z to test it before the test number.
9,? Variable contains the exit status of the previously executed command (the most recently completed foreground process) (can be used to detect exit status)


Common parameters:
File/directory judgment:
[-A file] is true if file exists.
[-B file] Returns true if file exists and is a block file.
[-C file] Returns True if file is present and is a character.
[-D file] Returns true if file exists and is a directory.
[-E File] Returns true if the specified file or directory exists.
[-F file] Returns True if file exists and is a normal file.
[-G file] Returns True if file exists and Sgid is set.
[-H file] Returns True if file exists and is a symbolic symlink. (This option is not available on some older systems)
[-K file] Returns true if file exists and the adventure bit has been set.
[-P file] Returns True if file is saved and is a command pipeline.
[-R File] Returns true if file exists and is readable.
[-S file] Returns true if file exists and non-0 o'clock is true.
[-U FILE] Returns true if file exists and the SUID bit is set.
[-W file] Returns True if file exists and is writable. (a directory must be executable for its content to be accessed)
[-X file] Returns true if file exists and is executable.
[-o file] Returns true if file exists and is a valid user ID.
[-G file] Returns True if file exists and the default group is the current group. (Check system default group only)
[-L file] Returns 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 returns to True.
[-S file] Returns true if file exists and is a socket.
[File1-nt FILE2] Returns True if FILE1 is newer than FILE2, or FILE1 exists but FILE2 does not exist.
[File1-ot FILE2] If FILE1 is older than FILE2, or FILE2 exists but FILE1 does not exist then return to true.
[File1-ef FILE2] returns True if FILE1 and FILE2 point to the same device and node number.


String judgments
[-Z string] Returns True if the length of the string is zero, that is, NULL is true
[-N string] If the length of a string is nonzero then it returns true, that is, non-null is True
[STRING1] Returns True if the string is not empty, similar to-n
[STRING1 = = STRING2] Returns True if two strings are the same
[STRING1! = STRING2] Returns True if the string is not the same
[STRING1 < STRING2] if the "STRING1" dictionary is sorted before "STRING2" the return is true.
[STRING1 > STRING2] If the "STRING1" dictionary is sorted after "STRING2", the return is true.


Numerical judgment
[Int1-eq INT2] INT1 and INT2 two number equal return to True, =
[Int1-ne INT2] INT1 and INT2 two numbers return to true,<>
[Int1-gt INT2] INT1 greater than INT2 returns to true,>
[Int1-ge INT2] INT1 greater than or equal to INT2 returns to True, >=
[Int1-lt INT2] INT1 less than INT2 returns to true,<
[Int1-le INT2] INT1 is less than or equal to INT2 returns to True, <=


Logical judgment
[ ! Expr] is not logical and returns true if expr is false.
[Expr1-a EXPR2] logic with, if EXPR1 and EXPR2 all true then return to true.
[Expr1-o EXPR2] logic or, if EXPR1 or EXPR2 is true then return to true.
[  ] || [] combine two conditions with or
[] && [] combine two conditions with and


Other judgments
[-T FD] If the file descriptor FD (the default value is 1) is turned on and pointing to a terminal returns to True
[-O optionname] returns true if Shell option Optionname is turned on


If Advanced Features:
Double parenthesis (()): Represents a mathematical expression
In the judgment command, only simple arithmetic operations are allowed in the comparison, and the double parentheses provide more mathematical symbols, and the ' > ' in the double parenthesis, ' < ' does not need to be transferred.

square brackets [[]]: represents advanced string processing functions
The judgment command in both brackets uses a standard string comparison, and you can also use a matching pattern to define a regular expression that matches a string.

The effect of double brackets:
In the shell, [$a! = 1 | | $b = 2] is not allowed, to be used [$a! = 1] | | [$b = 2], and the double brackets can solve the problem, [[$a! = 1 | | $b = 2]]. Another example of this ["$a"-lt "$b"], can also be changed to the form of double brackets (("$a" < "$b"))


Instance
1: Determine if the directory $doiido exists, if it does not exist, create a new
if [!-D "$doiido"]; then
mkdir "$doiido"
Fi

2: Determine whether the ordinary file $doiido, if not exist, create a new
if [!-F "$doiido"]; then
Touch "$doiido"
Fi

3: Determine if $doiido exists and has executable permissions
IF [!-X "$doiido"]; then
mkdir "$doiido"
chmod +x "$doiido"
Fi

4: Is to judge whether the variable $doiido has a value
if [!-n "$doiido"]; then
echo "$doiido is empty"
Exit 0
Fi

5: Two variables are judged equal
if ["$var 1" = "$var 2"]; then
Echo ' $var 1 eq $var 2 '
Else
Echo ' $var 1 not EQ $var 2 '
Fi

6: Test exit Status:
if [$?-eq 0];then
Echo ' That's OK '
Fi

7: Comparison of values:
If ["$num"-GT "150"]
echo "$num is biger than 150"
Fi

8:a>b and A<c
(( a > B)) && ((a < C))
[[$a > $b] && [[$a < $c]]
[$a-gt $b-a $a-lt $c]

9:a>b or A<c
((a > B)) | | ((a < C))
[$a > $b] | | [$a < $c]
[$a-gt $b-o $a-lt $c]

10: Detect the user who executed the script
if ["$ (whoami)"! = ' root ']; then
echo "You had no permission to run $ as Non-root user."
Exit 1;
Fi
The above statement can also use the following refinement statements
["$ (whoami)"! = ' root '] && (echo "You are permission to run $ as Non-root user."; exit 1)

11: Regular Expression
doiido= "Hero"
if [["$doiido" = = h*]];then
echo "Hello,hero"
Fi


============Other examples ============
1. View the current operating system type
#!/bin/sh
System= ' Uname-s '
if [$SYSTEM = "Linux"]; Then
echo "Linux"
elif [$SYSTEM = "FreeBSD"]; Then
echo "FreeBSD"
elif [$SYSTEM = "Solaris"]; Then
echo "Solaris"
Else
echo "What?"
Fi

2. If use read to pass the argument to judge
#!/bin/bash
Read-p "Please input a score:" Score
Echo-e "Your score [$score] is judging by SYS now"

If ["$score"-ge "0"]&&["$score"-lt "];then
echo "Sorry,you is lost!"
elif ["$score"-ge "]&&[" $score "-lt" "];then"
echo "Just soso!"
elif ["$score"-le "]&&[" $score "-ge" "];then"
echo "Good job!"
Else
echo "Input score is wrong, the range is [0-100]!"
Fi

3. Determine if the file exists
#!/bin/sh
Today= ' date-d yesterday +%y%m%d '
File= "Apache_$today.tar.gz"
Cd/home/chenshuo/shell
If [-F "$file"];then
echo "OK"
Else
echo "Error $file" >error.log
Mail-s "fail backup from test" [email protected] <error.log
Fi

4. 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
weekoffset=$[$ (date + "%V")% 2]

If [$WEEKOFFSET-eq "0"]; Then
echo "Sunday evening, put out the garbage cans." | Mail-s "garbage cans out" [Email protected]_domain.org
Fi

5. Mount the hard disk script (NTFS format hard disk under Windows)
#! /bin/sh
Dir_d=/media/disk_d
Dir_e=/media/disk_e
Dir_f=/media/disk_f

A= ' ls $dir _d | Wc-l '
b= ' ls $dir _e | Wc-l '
c= ' ls $dir _f | Wc-l '

echo "Checking disk_d ..."
If [$a-eq 0]; Then
echo "Disk_d is not exsit,now creating ..."
sudo mount-t ntfs/dev/disk/by-label/software/media/disk_d
Else
echo "Disk_d exits"
Fi

echo "Checking disk_e ..."
If [$b-eq 0]; Then
echo "Disk_e is not exsit,now creating ..."
sudo mount-t ntfs/dev/disk/by-label/elitor/media/disk_e
Else
echo "Disk_e exits"
Fi

echo "Checking disk_f ..."
If [$c-eq 0]; Then
echo "Disk_f is not exsit,now creating ..."
sudo mount-t ntfs/dev/disk/by-label/work/media/disk_f
Else
echo "Disk_f exits"
Fi

The IF condition of the Linux shell script is judged

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.