shell conditional expressions

 

1. The common syntax for conditional testing is as follows

1. test test expression

2. [Test expression] #There needs to be spaces on both sides

3. [[ test expression]]

4. ((test expression))

illustrate:

The first and second are equivalent, and the third is an extended test command. Syntax 4 is often used to calculate

In [[]] double brackets, wildcards can be used for pattern matching, and operators such as && || > < can be directly applied to double brackets, but not single brackets

 

2. The simple example of test is as follows, you can check man test for detailed help

[root@backup ~]# test -f /etc/passwd && echo 1 || echo 0
1
[root@backup ~]# test -f /etc/passwd11 && echo 1 || echo 0
0

 

3, [] but the bracket example

[root@backup ~]# [ -f /etc/passwd ]&& echo 1 || echo 0
1
[root@backup ~]# [ -f /etc/passwd11 ]&& echo 1 || echo 0
0

4. Example of [[]] double square brackets

[root@backup ~]# [[ 3 > 2 ]]&& echo 1 || echo 0
1
[root@backup ~]# [[ 3 > 4 ]]&& echo 1 || echo 0
0

5. File test expressions

 

[root@backup ~]# [ -d /etc/ ]&& echo 1 || echo 0
1
[root@backup ~]#
[root@backup ~]# [ -d /etc/11 ]&& echo 1 || echo 0
0

6. String test expressions

 

[root@backup ~]# [ -n "abc" ]&& echo 1 || echo 0
1

[root@backup ~]# [ -z " " ]&& echo 1 || echo 0
0
[root@backup ~]# [ "ab" = "ab" ]&& echo 1 || echo 0
1
[root@backup ~]# [ "ab" != "ab" ]&& echo 1 || echo 0
0

 Observe how the system script is written

 

7. Integer comparison

[root@backup ~]# [ 2 -lt 3 ]&&echo 1||echo 0
1
[root@backup ~]# [ 2 -gt 3 ]&&echo 1||echo 0
0

Compare the size of two integers
[root@backup ~]# cat 1.sh 
#!/bin/bash
#no.1
a=$1
b=$2
[ $# -ne 2 ]&&{
  echo "USAGE:"$0 "num1 num2"
  exit 1
}
#no.2
expr $a + 10  &>/dev/dull
RETVAL1=$?
expr $b + 10 &>/dev/dull
RETVAL2=$?
[ $RETVAL1 -eq 0 -a $RETVAL2 -eq 0 ]||{
  echo "pls input two int nums: "  exit 2
}

#no.3
[ $a -gt $b ] && echo "$a>$b"||{
[ $a -eq $b ] && echo "$a=$b"||echo "$a<$b"

}
[root@backup ~]# sh 1.sh 1 2
1<2
[root@backup ~]# sh 1.sh 3 2
3>2
[root@backup ~]# sh 1.sh 2 2
2=2


改用read方式

[root@backup ~]# cat 1.sh
#!/bin/bash
#no.1
read -p "Pls input two num: " a b
[ -z "$a" ]||[ -z "$b" ]&&{
echo "pls input two num again"
exit 1
}
#no.2
expr $a + 10 &>/dev/dull
RETVAL1=$?
expr $b + 10 &>/dev/dull
RETVAL2=$?
test $RETVAL1 -eq 0 -a $RETVAL2 -eq 0 ||{
echo "pls input two int nums: "
exit 2
}

 
 

#no.3
[ $a -gt $b ] && echo "$a>$b"
[ $a -lt $b ] && echo "$a<$b"
[ $a -eq $b ] && echo "$a=$b"

 
 

[root@backup ~]# sh 1.sh
Pls input two num: 1 1
1=1
[root@backup ~]# sh 1.sh
Pls input two num: 1 2
1<2
[root@backup ~]# sh 1.sh
Pls input two num: 2 1
2>1

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326504982&siteId=291194637