How to use the IF statement for the Linux Shell script programming (conditional judgment)

Source: Internet
Author: User

If statement format
If condition
Then
Command
Else
Command
Fi, don't forget this ending.
If statement forget the end fi
Test.sh:line 14:syntax error:unexpected End of fi if three conditional expressions

If
Command
Then if
Function
Then
Command execution succeeds, equals return 0 (e.g. grep, match found)
Execution failed, return non 0 (grep, no match found)
if [Expression_r_r_r]
Then the result of the expression is true, then the return 0,if the 0 value to then
if test Expression_r_r_r
Then the result of the expression is false, then return non-0,if the non-0 value to then
[] &&--shortcut if
[-F "/etc/shadow"] && echo "This computer uses Shadow Passwors"
&& can be understood as then
If the expression on the left is true then the statement on the right side of the shell differs from the function of the If of the C language.

Shell if C language if
0 is true, go then just the opposite, not 0 go then
Integer variables are not supported directly if
Must: If [I–ne 0] But support string variable direct if
If [str] If the string is not 0
Supports variable direct if
if (i)


Use multiple command or function as the IF condition

Copy CodeThe code is as follows:
Echo–n "Input:"
Read user if
Multiple directives, which are equivalent to "and" (with)
grep $user/etc/passwd >/tmp/null
Who-u | grep $user
Then the command above executes successfully, the return value $? For 0,0 to True, run then
echo "$user has logged"
else instruction execution failed, $1, run else
echo "$user have not logged"
Fi
# sh test.sh
Input:macg
MACG pts/0 May 15 15:55. 2075 (192.168.1.100)
MACG has logged

# sh test.sh
Input:ddd
DDD have not logged takes a function as an if condition (the function is equivalent to command, the advantage of the function is that its return value can be customized)

If
With the function as the IF condition,
Getyn
Then function reture value 0 is true, go then
echo "Your answer is yes"
else function return value is not 0 false, go else
echo "Your anser is no"
is the fi if command equivalent to Command+if $?

$ VI testsh.sh
#!/bin/sh if
Cat 111-tmp.txt | grep ting1
Then
Echo found
Else
echo "No found"
Fi
$ VI testsh.sh
#!/bin/sh Cat 111-tmp.txt | grep ting1
If [$?-eq 0]
Then
echo $?
Echo found
Else
echo $?
echo "No found"
Fi
$ sh testsh.sh
No found $ sh testsh.sh
1
No found
$ VI 111-tmp.txt
That is 222file
THISTING1 is 111file $ sh testsh.sh
Thisting1 is 111file
Found
$ VI 111-tmp.txt
That is 222file
THISTING1 is 111file $ sh testsh.sh
Thisting1 is 111file
0
Found

Traditional if from sentence--with conditional expression as the IF condition

Copy CodeThe code is as follows:
If [conditional expression]
Then
Command
Command
Command
Else
Command
Command
Fi



Conditional expressions

If [-f file] exists
If [-D ...] If the directory exists
If [-S file] If the file exists and is not empty
If [-R File] is present and readable
If [w file] is present and writable
If [-X file] If the file exists and is executable
If [Int1-eq Int2] if int1 equals Int2
If [Int1-ne Int2] if not equal to
If [Int1-ge Int2] If >=
If [int1-gt Int2] If >
If [Int1-le Int2] If <=
If [int1-lt Int2] If <

string-Variable expression

Copy CodeThe code is as follows:
if [$a = $b] if string1 equals string2
string allows an equal sign with an assignment number
if [$string 1! = $string 2] If string1 is not equal to string2
If [-n $string] returns 0 (true) if string is non-null (not 0)
If [-Z $string] if string is empty
If [$sting] if string is not NULL, return 0 (and-n-like) conditional expression reference variable to take with $

if [a = b]; then
echo Equal
Else
Echo No equal
Fi
[Email protected] ~]$ sh test.sh
Input A:
5
Input B:
5
No equal (equals expression not compared to $ A and $b, but compared with a and B, natural a!=b) corrected:
if [$a = $b]; then
echo Equal
Else
Echo No equal
Fi
[Email protected] ~]$ sh test.sh
Input A:
5
Input B:
5
Equal
-eq-ne-lt-nt can only be used for integers, not strings, and string equals with an assignment number =
[Email protected] ~]$ VI test.sh
Echo-n "Input your choice:"
Read Var
If [$var-eq "yes"]
Then
Echo $var
Fi
[Email protected] ~]$ sh-x test.sh
Input your choice:
Y
Test.sh:line 3:test:y: integer expression_r_r_r expected
Expected integer form, that is,-eq does not support string = placed elsewhere is an assignment, placed in if [] is the string equals, the shell does not have = =, that is the C language equals
String without spaces, can be added "", can also not add

[Email protected] ~]$ VI test.sh
echo "Input A:"
Read a
echo "Input is $a"
if [$a = 123]; Then
Echo equal123
Fi
[Email protected] ~]$ sh test.sh
Input A:
123
Input is 123
equal123 = When equal, both sides must have a space, otherwise it fails
The equal sign is also an operator, must and other variables, keywords, with an empty Geggai (equal sign when the assignment number is exactly the opposite, there can be no space on both sides)

[Email protected] ~]$ VI test.sh echo "Input your choice:"
Read Var
if [$var = "yes"]
Then
Echo $var
echo "Input is correct"
Else
Echo $var
echo "Input Error"
Fi
[Email protected] ~]$ VI test.sh echo "Input your choice:"
Read Var
if [$var = "yes"] add a space on both sides of the equal sign
Then
Echo $var
echo "Input is correct"
Else
Echo $var
echo "Input Error"
Fi
[Email protected] ~]$ sh test.sh
Input your choice:
Y
Y
Input is correct
[Email protected] ~]$ sh test.sh
Input your choice:

N
Input is correct
The wrong way to go then, all go then, why?
Because if the $var= "yes" is read as a variable, and this variable is empty, return 1, then go else [[email protected] ~]$ sh test.sh
Input your choice:
Y
Y
Input error
[Email protected] ~]$ sh test.sh
Input your choice:
No
No
Input error
All normal if [$ANS] is equivalent to if [-N $ANS]
If the string variable is not empty (then), empty (else)

echo "Input your choice:"
Read ANS if [$ANS]
Then
Echo No empty
Else
Echo empth
Fi
[Email protected] ~]$ sh test.sh
Input your choice: enter

Empth description "Carriage return" is an empty string
[Email protected] ~]$ sh test.sh
Input your choice:
34
No empty
Integer conditional expressions, greater than, less than, no > and < in the shell, will be treated as angle brackets, only-ge,-gt,-le,lt
[Email protected] ~]$ VI test.sh echo "input A:"
Read a
If [$a-ge 100]; Then
Echo 3bit
Else
Echo 2bit
Fi
[Email protected] ~]$ sh test.sh
Input A:
123
3bit
[Email protected] ~]$ sh test.sh
Input A:
20
2bit integer operation symbol-GE,-GT,-LE,-LT, don't forget to add-

if test $a GE 100; then [[email protected] ~]$ sh test.sh
Test.sh:line 4:test:ge:binary operator expected
if test $a-ge 100; then [[email protected] ~]$ sh test.sh
Input A:
123
3bit

Logical Non! The opposite of the conditional expression
if [! expression]
if [!-D $num] If there is no directory $num
The juxtaposition of logical and –a conditional expressions
If [expression 1–a-expression 2]
Logical OR-o conditional expression or
If [expression 1–o-expression 2]

Logical Expressions

The expression is combined with the preceding =! =-d–f–x-ne-eq-lt
Logical symbols are normally followed by other expressions, without any parentheses (), which are tied
If [-z] $JHHOME "-a-d $HOME/$num]
Note logic with-A and logic or-O is easy to confuse with other string or file operation symbols
The most common form of assignment, pre-assignment = Both sides of the variable are evaluated
Whether the left variable is empty, the right side of the directory (value) exists (value is valid)

Copy CodeThe code is as follows:
[Email protected] ~]$ VI test.sh
:
echo "Input the num:"
Read num
echo "Input is $num" if [-Z "$JHHOME"-a-d $HOME/$num] If the variable $jhhome is empty and $home/$num directory exists
Then
Jhhome= $HOME/$num is assigned
Fi
echo "Jhhome is $JHHOME"
-----------------------
[Email protected] ~]$ sh test.sh
Input the num:

Input is PPP
Jhhome is directory-D $HOME/$num does not exist, so $jhhome is not assigned
[[email protected] ~]$ mkdir PPP
[Email protected] ~]$ sh test.sh
Input the num:

Input is PPP
Jhhome IS/HOME/MACG/PPP An example of-O, which reveals that the "=" must be left blank on both sides of the problem

echo "Input your choice:"
Read ANS if [$ANS = "yes"-o $ANS = "yes"-o $ANS = "y"-o $ANS = "Y"]
Then
Ans= "Y"
Else
Ans= "n"
Fi
Echo $ANS
[Email protected] ~]$ sh test.sh
Input your choice:

Y
[Email protected] ~]$ sh test.sh
Input your choice:
No
Y
Why the input is not yes and the result is still Y (go then)
Because = is read, the variable $ans= "Yes", and the variable is empty, so go else
[Email protected] ~]$ VI test.sh echo "Input your choice:"
Read ANS echo "Input your choice:"
Read ANS
if [$ANS = "yes"-o $ANS = "yes"-o $ANS = "y"-o $ANS = "Y"]
Then
Ans= "Y"
Else
Ans= "n"
Fi
Echo $ANS
[Email protected] ~]$ sh test.sh
Input your choice:
No

[Email protected] ~]$ sh test.sh
Input your choice:
Yes
Y
[Email protected] ~]$ sh test.sh
Input your choice:
Y
Y =================== with the test conditional expression as the IF condition ===================================
if test $num-eq 0 equivalent to if [$num –eq 0]
Test expression, no []
if test $num-eq 0
Then
echo "Try Again"
Else
echo "Good"
Fi
Mans test

[[email protected] ~]$ man test
[(1) User Commands [(1) Synopsis
Test EXPRESSION
[EXPRESSION]
[-N] STRING
The length of STRING is nonzero-n and direct $str are non-0 conditions
-Z STRING
The length of STRING is zero
STRING1 = STRING2
The strings is equal
STRING1! = STRING2
The strings is not equal
Integer1-eq INTEGER2
INTEGER1 is equal to INTEGER2
Integer1-ge INTEGER2
INTEGER1 is greater than or equal to INTEGER2
INTEGER1-GT INTEGER2
INTEGER1 is greater than INTEGER2
Integer1-le INTEGER2
INTEGER1 is less than or equal to INTEGER2
Integer1-lt INTEGER2
INTEGER1 is less than INTEGER2
Integer1-ne INTEGER2
INTEGER1 isn't equal to INTEGER2
File1-nt FILE2
FILE1 is newer (modification date) than FILE2
File1-ot FILE2
FILE1 is older than FILE2
-B FILE
FILE exists and is block special
-C FILE
FILE exists and is character special
-D FILE
FILE exists and is a directory
-E FILE
File exists files exist
-F FILE
File exists and is a regular file files exist and are normal files
-H FILE
FILE exists and is a symbolic link (same as-l)
-L FILE
FILE exists and is a symbolic link (same as-h)
-G FILE
FILE exists and is owned by the effective group ID
-O FILE
FILE exists and is owned by the effective user ID
-P FILE
FILE exists and is a named pipe
-S FILE
FILE exists and has a size greater than zero
-S FILE
FILE exists and is a socket
-W FILE
FILE exists and is writable
-X FILE
FILE exists and is executable

The most commonly used simplified if statement

&& if "front", then "back"

Copy CodeThe code is as follows:
[-f/var/run/dhcpd.pid] && rm/var/run/dhcpd.pid Check if the file exists, delete it if it exists

|| If it is not "front", the following

Copy CodeThe code is as follows:
[-F/USR/SBIN/DHCPD] | | Exit 0 Checks whether the file exists and exits if it exists

Use simplified if and $1,$2,$3 to detect parameters and call Help when unreasonable

Copy CodeThe code is as follows:
[-Z "$"] && help if the first parameter does not exist (-Z string length is 0)
["$" = "-H"] && help if the first parameter is-H, the help is displayed

Example

Copy CodeThe code is as follows:


#!/bin/sh
[-F "/etc/sysconfig/network-scripts/ifcfg-eth0"] && rm-f/etc/sysconfig/network-scripts/ifcfg-eth0
CP Ifcfg-eth0.bridge/etc/sysconfig/network-scripts/ifcfg-eth0
[-F "/etc/sysconfig/network-scripts/ifcfg-eth1"] && rm-f/etc/sysconfig/network-scripts/ifcfg-eth1
CP Ifcfg-eth1.bridge/etc/sysconfig/network-scripts/ifcfg-eth1
[-F "/etc/sysconfig/network-scripts/ifcfg-eth0:1"] && rm-f/etc/sysconfig/network-scripts/ifcfg-eth0:1

How to use the IF statement for the Linux Shell script programming (conditional judgment)

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.