Comparison and judgment are the elements of program flow control. This article summarizes shell comparison and judgment statements for ease of searching and using.
1. Important comparison Operators
Greater than:-GT
Less than:-lt
Greater than or equal to:-Ge
Less than or equal to:-le
Equal to:-EQ
Not equal to:-ne
Example:
If [$ var-EQ 0] # If $ VaR is equal to 0
If [$ var-Ne 0-A $ var-GT 2] # logic and-
If [$ var-Ne 0-o $ var-GT 2] # logic or-o
2. File-related judgment test
[-F $ file_var]: returns true if $ file_var is an existing file path or file name;
[-X $ var]: returns true if $ VaR has the file executable permission;
[-D $ var]: returns true if $ VaR is a directory;
[-E $ var]: returns true if $ VaR is an existing file;
[-C $ var]: returns true if $ VaR is an existing character device file;
Attached English:
-A file exists.
-B file exists and is a block special file.
-C file exists and is a character special file.
-D file exists and is a directory.
-E file exists (just the same as-).
-F file exists and is a regular file.
-G file exists and has its setgid (2) bit set.
-G file exists and has the same group ID as this process.
-K file exists and has its sticky bit set.
-L file exists and is a symbolic link.
-N string length is not zero.
-O named option is set on.
-O file exists and is owned by the user ID of this process.
-P file exists and is a first in, first out (FIFO) special file or Named Pipe.
-R file exists and is readable by the current process.
-S file exists and has a size greater than zero.
-S file exists and is a socket.
-T file descriptor number Fildes is open and associated with Terminal device.
-U file exists and has its setuid (2) bit set.
-W file exists and is writable by the current process.
-X file exists and is executable by the current process.
-Z string length is zero.
Example:
Fpath = "etc/passwd"
If [-e $ fpath]; then
Echo "file exists ";
Else
Echo "not exist ";
Fi
3. String comparison
[[$ Str1 = $ str2]: returns true if str1 is equal to str2;
[[$ Str1 = $ str2]: This is another way to judge whether a string is equal;
[[$ Str1! = $ Str2]: returns true if str1 is not equal to str2;
[[$ Str1> $ str2]: returns true if str1 is greater than str2;
[[$ Str1 <$ str2]: returns true if str1 is smaller than str2;
[[-Z $ str1]: returns true if str1 contains a null string;
[[-N $ str1]: returns true if str1 contains a non-null string;
Shell comparison and judgment