Computation‎ > ‎

UNIX Operators and Test Conditions

There are a large number of logical tests you might want to make in an analytical process

Arithmetic
 Operator Description Example
 + Addition
 $ expr 2 + 2
4
 - Subtraction $ expr 8 - 3
5
 * Multiplication $ expr 3 \* 7  (NOTE you need to escape the *)
21
 /Division  $ expr 15 / 4
3
 $ expr 15 / 3
5
 %Modulus  $ expr 15 % 6
3
 $ expr 15 % 3
0
 = Assignment 
 == Equality Test 
 != Not Equality Test 

Numeric Operators
 Operator Description Example
 -eq Check if Equal [ 5 -eq 5 ] is True
 [ 5 -eq 4 ] is Not True
 -ne Check if NOT Equal [ 5 -ne 5 ] is Not True
 [ 5 -ne 4 ] is True
 -gt Check if Left > Right [ 5 -gt 4 ] is True
 -lt Check if Left < Right [ 5 -lt 4 ] is Not True
 -ge Check if Left >= Right [ 5 -ge 5 ] is True
 [ 5 -ge 4 ] is True
 -le Check if Left <= Right [ 5 -le 5 ] is True
 [ 5 -le 4 ] is Not True

Boolean Operators for Numeric Comparisons
 Operator Description Example
 ! Inverts True to False OR False to True 
 -o Logical OR, if any one test is true then true [ 5 -ne 5 -o 5 -lt 4 ] is Not True
 -a Logical AND, if all tests are true then true [ 5 -eq 5 -a 5 -gt 4 ] is True

String Operators
variable=KeatsLab
 Operator    Description Example 
 = Tests if two operands are equal [ Jonathan = Keats ] is Not True
 != Test if two operands are NOT equal [ Jonathan != Keats ] is True
 -z Test if the string is 0 length (IS EMPTY) [ -z $variable ] is Not True
 -n Test if the string is >= 1 length (NOT EMPTY) [ -n $variable ] is True
 str Test if the string is empty [ $variable ] is Not True

File Test Operators
 Operator Description Example
 -b Test if block special file [ -b file ]
 -c
 Test if character special file [ -c file ] 
 -d Test if name is a directory [ -d file ]
 -f Test if ordinary file, NOT directory OR special file [ -f file ]
 -g Test if file has group ID bit set 
 -k Test if file has sticky bit set 
 -p Test if file is a named pipe 
 -t Test if file is open 
 -u Test if file has user ID bit set 
 -r Test if file is readable [ -r file ]
 -w Test if file is writeable [ -w file ]
 -x Test if file is executable [ -x file ]
 -s Test if file has >0 bytes [ -s file ]
 -e Test if file OR directory exists. [ -e file ]

Code Examples
why us [] versus () for tests?


Tests
Comments