If condition judgment of Linux shell script, linuxshell

Source: Internet
Author: User

If condition judgment of Linux shell script, linuxshell
IF condition judgment

1. Basic Syntax:
If [command]; then
Statements that meet this condition
Fi


2. Extended Syntax:
If [command]; then
Statements that meet this condition
Elif [command]; then
Statements that meet this condition
Else
Statements that meet this condition
Fi

3. syntax description:
Bash shell will execute the if statement in sequence. if the command is executed and its return status is 0, it will execute the statement that meets this condition. Otherwise, the subsequent command will not be executed, jump to the next command.
When multiple nesting statements exist, only the first command that returns the 0 exit state will execute the statement that meets the condition. If the execution status of all statements is not 0, then execute the statement in else.
Return status: the exit status of the last command, or 0 if no conditions are true.


Note:
1. [] indicates a condition test. Note that spaces are important. Note that there must be spaces before '[' and ']'.
2. In shell, then and fi are separate statements. If you want to enter data in the same line, separate them with semicolons.
3. Pay attention to the processing of variables in if judgment. quotation marks are required to avoid unnecessary errors. If no double quotation marks are added, some string variables containing spaces are judged incorrectly. For example, if [-n "$ var"] is empty, an error occurs.
4. The judgment does not support floating point values.
5. If you only use the ">" or "<symbol, the system considers it as an output or an input redirection. Although the result is correctly displayed, it is actually incorrect. Therefore, you need to convert these symbols.
6. By default, the error message generated by running the command in the if statement still appears in the output result of the script.
7. When you use-z or-n to check the length, the variable that is not defined is also 0.
8. Empty variables and uninitialized variables may have a catastrophic impact on shell script testing. Therefore, when you are not sure about the variable content, run the-n or-z command before the test number.
9 ,? The variable contains the exit status of the previously executed command (the last completed foreground process) (which can be used to detect the exit status)


Common parameters:
File/directory judgment:
[-A FILE] true if the FILE exists.
[-B FILE] If the FILE exists and is a block FILE, the return value is true.
[-C FILE] If the FILE exists and is a character FILE, the return value is true.
[-D FILE] If the FILE exists and is a directory, the return value is true.
[-E FILE] returns true if the specified FILE or directory exists.
[-F FILE] If the FILE exists and is a common FILE, the return value is true.
[-G FILE] If the FILE exists and the SGID is set, the return value is true.
[-H FILE] If the FILE exists and is a symbolic link FILE, the return value is true. (This option is invalid in some old systems)
[-K FILE] If the FILE exists and an adventure bit has been set, the return value is true.
[-P FILE] returns true if the FILE is stored in a command pipeline.
[-R FILE] If the FILE exists and is readable, the return value is true.
[-S FILE] If the FILE exists and the size is not 0, the return value is true.
[-U FILE] If the FILE exists and the SUID bit is set, the return value is true.
[-W FILE] If the FILE exists and is writable, the return value is true. (A directory is accessible for its content)
[-X FILE] If the FILE exists and is executable, the return value is true.
[-O file] returns true if the FILE exists and belongs to a valid user ID.
[-G file] If FILE exists and the default group is the current group, true is returned. (Only check the default system group)
[-L file] If the FILE exists and is a symbolic connection, the return value is true.
[-N file] If the FILE exists and has been mod, if ied since it was last read, true is returned.
[-S file] If the FILE exists and is a socket, the return value is true.
[FILE1-nt FILE2] returns true if FILE1 is newer than FILE2, or if FILE1 exists but FILE2 does not exist.
[FILE1-ot FILE2] If FILE1 is older than FILE2, or FILE2 exists but FILE1 does not exist, true is returned.
[FILE1-ef FILE2] If FILE1 and FILE2 point to the same device and node number, true is returned.


String judgment
[-Z STRING] returns true if the STRING length is zero, that is, null is true.
[-N STRING] If the STRING length is non-zero, the return value is true, that is, the non-null value is true.
[STRING1] returns true if the string is not null, similar to-n.
[STRING1 = STRING2] returns true if the two strings are the same
[STRING1! = STRING2] returns true if the strings are different
[STRING1 <STRING2] returns true if the "STRING1" dictionary is sorted before "STRING2.
[STRING1> STRING2] returns true if the "STRING1" dictionary is sorted after "STRING2.


Value Judgment
[INT1-eq INT2] INT1 and INT2 are equal, returns true, =
[INT1-ne INT2] INT1 and INT2 return true, <>
[INT1-gt INT2] If INT1 is greater than INT2, true is returned.>
[INT1-ge INT2] If INT1 is greater than or equal to INT2, true is returned,> =
[INT1-lt INT2] INT1 less than INT2 returns true, <
[INT1-le INT2] If INT1 is less than or equal to INT2, true is returned. <=


Logical judgment
[! EXPR] logic is not. If EXPR is false, true is returned.
[EXPR1-a EXPR2] logic and returns true if EXPR1 and EXPR2 are all true.
[EXPR1-o EXPR2] logic or, if EXPR1 or EXPR2 is true, return true.
[] | [] Use OR to merge two conditions
[] & [] Use AND to merge two conditions


Other judgments
[-T FD] If the file descriptor FD (default value: 1) is opened and points to a terminal, the return value is true.
[-O optionname] returns true if the shell option optionname is enabled.


IF advanced features:
Parentheses (): A mathematical expression.
In the Judgment command, only simple arithmetic operations can be performed in the comparison, while the double parentheses provide more mathematical symbols, and '>' in the double parentheses ', '<' does not need to be converted.

Brackets [[]: indicates the advanced string processing function.
The matching mode can be used to define the regular expression that matches the string.

The role of parentheses:
In shell, [$! = 1 | $ B = 2] is not allowed, use [$! = 1] | [$ B = 2], and the double brackets can solve this problem. [[$! = 1 | $ B = 2]. For example, this ["$ a"-lt "$ B"] can also be changed to the double brackets ("$ a" <"$ B "))


Instance
1: Determine whether the directory $ doiido exists. If not, create a new
If [! -D "$ doiido"]; then
Mkdir "$ doiido"
Fi

2: Determine whether a common file $ doiido is saved. If it does not exist, create a new one.
If [! -F "$ doiido"]; then
Touch "$ doiido"
Fi

3: Determine whether $ doiido exists and has executable permissions
If [! -X "$ doiido"]; then
Mkdir "$ doiido"
Chmod + x "$ doiido"
Fi

4: determines whether the variable $ doiido has a value.
If [! -N "$ doiido"]; then
Echo "$ doiido is empty"
Exit 0
Fi

5. Determine whether two variables are equal.
If ["$ var1" = "$ var2"]; then
Echo '$ var1 eq $ var2'
Else
Echo '$ var1 not eq $ var2'
Fi

6: test exit status:
If [$? -Eq 0]; then
Echo 'that is 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: Check the user executing the script
If ["$ (whoami )"! = 'Root']; then
Echo "You have no permission to run $0 as non-root user ."
Exit 1;
Fi
The preceding statement can also use the following short statement
["$ (Whoami )"! = 'Root'] & (echo "You have no permission to run $0 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, using the read parameter to determine
#! /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 "60"]; then
Echo "sorry, you are lost! "
Elif ["$ score"-ge "60"] & ["$ score"-lt "85"]; then
Echo "just soso! "
Elif ["$ score"-le "100"] & ["$ score"-ge "85"]; then
Echo "good job! "
Else
Echo "input score is wrong, the range is [0-100]! "
Fi

3. Determine whether a 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" loveyasxn924@126.com <error. log
Fi

4. This script is executed by cron every Sunday. If the number of weeks is even, he will remind you to clear the garbage bins:
#! /Bin/bash
WEEKOFFSET = $ [$ (date + "% V") % 2]

If [$ WEEKOFFSET-eq "0"]; then
Echo "Sunday evening, put out the garbage cans." | mail-s "Garbage cans out" your@your_domain.org
Fi

5. Mount the hard disk script (ntfs hard disk in 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

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.