Judgment statement
Use test to make judgments
# test [option] filetest -d /Users/zhanghe/desktop/user/shell
Example:
#If the file is a directory, output yes, otherwise output notest -d /Users/zhanghe/desktop/user/shell && echo yes || echo no
Options
Judging by file type
-d Determine whether the file exists,And it is a directory -e Determine whether the file exists -f Determine whether the file exists,And it is a normal file -s Determine whether the file exists,And whether it is a non-empty file -b Determine whether the file is a block device file -c Determine whether the file is a character device file -g Determine whether the file is setsetgidBit -h Determine whether the file is a symbolic link -L Determine whether the file is a symbolic link -p Determine whether the file is a pipeline file -u Determine whether the file is setsetuidBit #Exampletest -s
Judging by permissions
-r Determine whether the file exists,And whether you have read permission -w Determine whether the file exists,And whether you have write permissions -x Determine whether the file exists,And whether there is execution permission #Exampletest -w
Value comparison
-eq equal -ne 不equal -gt Greater than -lt Less than -ge Greater thanequal -le Less thanequal #Exampletest 1 -eq 2
String comparison
-z Determine whether the string is empty -n Determine whether the string is not empty == Determine whether two strings are equal != Determine whether the two strings are not equal #Exampletest "aa" == "ab"
Logical judgment
-a Logic and -o Logical or ! Logical non-logical #Exampletest "aa" == "aa" -a "ab" == "aa"
The above test can be replaced by [ ]
like:
[ -s ] [ "aa" == "ab" ]
There is also a [[ condition ]] that can also be used for conditional judgment. For test and [] if the expression contains special characters, it needs to be escaped, while for [[ condition ]], the influence of special characters is not required.But please note that there are at least one space character behind [[ and ]] before the front of [[
String contains
You can see that the above provides only basic judgments, so how to judge if the string contains
Use grep
if [[ -n `echo "abcd" | grep "ab"` ]] then echo "Include" fi
Use wildcards
if [[ "abcd" == *ab* ]] then echo "Include" fi
The above is the detailed content of the shell judgment statement. For more information about shell judgment statements, please pay attention to my other related articles!