Operators
Arithmetic operators
#!/bin/bash

expr 1 + 3
expr 2 - 1
expr 2 \* 4 # escape wildcard character *
expr 4 / 2
expr 10 % 3

let z=5**3; echo $z # exponentiation

a=`expr 1 + 3`; echo $a
a=$(expr 1 + 3); echo $a
a=$(( 1 + 3 )); echo $a

let "a += 10"; echo $a # +=, -=, *=, /=, %=
(( ++a )); echo $a # ++, --
			
Logical operators
  • !, not
  • &&, and
  • ||, or
  • #!/bin/bash
    
    # <, <=, >, >=
    echo `expr 1 \< 3` # 1, true
    echo `expr 0 \> 2` # 0, false
    echo `expr 5 \!= 5` # 0
    echo `expr 5 == 5` # ==
    			
  • -eq, -ne, -gt, -lt, -ge, -le
  • #!/bin/bash
    
    a=10
    b=100
    
    if [ $a != $b ]
    then
    	echo "Not equal"
    fi
    
    if [ $a -lt $b ]
    then
    	echo "Less than"
    fi
    			
    Boolean operators
  • !, not
  • -a, and
  • -o, or
  • #!/bin/bash
    
    a=10
    b=100
    
    if [ $(($a % 2)) == 0 -a $a -gt 5 ]
    then
    	echo "Even and greater than five"
    fi
    			
    Bitwise operators
    #!/bin/bash
    
    a=1
    ((a <<= 1)); echo $a # 2
    a=$(( a << 1 )); echo $a # 4
    			
    Quotes
  • ", anything enclose in double quotes removed meaning of that characters (except \ and $)
  • ', enclosed in single quotes remains unchanged
  • `, to execute command
  • #!/bin/bash
    
    echo "Name: $USER" # Name: lchen
    echo 'Name: $USER' # Name: $USER
    echo `pwd` # /home/lchen
    echo "Today is `date`"
    			
    Reference