Summary of Linux Shell Operators

Linux Shell Operators

 

Operators in Shell can be divided into arithmetic operators, relational operators, Boolean operators, string operators and file test operators

 

1. Arithmetic operators

 

a=2, b=1

Operator Description Example
+ addition `expr $a + $b` # 3
- subtraction `expr $a - $b` # 1
* multiplication `expr $a \* $b` # 2, * need to be escaped
/ division `expr $a / $b' # 2
% remainder `expr $a % $b' # 0
= assign name=value
== equality comparison [ $a == $b ] # false
!= unequal comparison [ $a != $b ] # true 

 

Note: Conditional expressions should be placed between square brackets and spaces, e.g. [$a==$b] is wrong and must be written as [ $a == $b ]

2. Relational operators

Relational operators only support numbers, not strings, unless the value of the string is a number 

 

a=1, b=2

Operator Description Example
-eq determine whether it is equal [ $a -eq $b ] # false
-born are not equal [$ a -ne $ b] # true
-gt Is it greater than [ $a -gt $b ] # false
-lt Is it less than [ $a -lt $b ] # true
-give Is it greater than or equal to [ $a -ge $b ] # false
-the Is it less than or equal to [ $a -le $b ] # true

 

 

3. Boolean Operators

 

Operator Description Example
! NOT operation [ ! false ] returns true
-O OR operation [ true -o false ] returns true
-a AND operation [ true -a false] returns false

 

 

4. String operators

 a=abc, b=def

Operator Description Example
= Are they equal [ $a = $b ] # false
!= are not equal [ $a != $b ] # true
-with length is 0 [ -z $a ] # false
-n Whether the length is not 0 [ -n $a ] # true
str is empty [ $a ] # false

 

 

5. File Test Operator

 

The file test operator is used to detect various attributes of Unix files

 

Operator Description Example
-b file Is it a block device file [ -b $file ] 
-c file Is it a character device file [ -c $file ] 
-d file Is it a directory [ -d $file ]
-f file Is it a normal file (neither a directory nor a device file) [ -f $file ] 
-g file Whether the SGID bit is set [ -g $file ] 
-k file Whether the sticky bit is set (Sticky Bit) [ -k $file ]
-p file Is it a named pipe [ -p $file ]
-in the file Whether the SUID bit is set [-u $ file]
-r file Is it readable [ -r $file ]
-w file writable [ -w $file ]
-x file Is it executable [ -x $file ]
-s file Whether it is not empty (whether the file size is greater than 0), if not empty, return true [ -s $file ] 
-e file Whether the file (including the directory) exists [-e $ file] 

Guess you like

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