The Test in the UNIX Shell - Logical expressions and numbers
(Page 3 of 4 )
We can also link together logical expressions with either the && or || operators I introduced in my previous article, or leave this also to the test command. In this case, the expression will look as follows in the table:
Expression
Test checks for what trait?
! expression
True if the expression is false
expression_1 -a expression_2
True if both of the expressions are true; it's a logical and (-a).
expression_1 -o expression_2
True if either one of the expressions is true; it's a logical or (-o).
For example:
#If alfa is not a directory signal to the user
if test ! -d alfa 2>/dev/null
then
echo "alfa is not a directory Invalid input"
fi
if [ [ -f alfa ] -a [ -O alfa ] ]
then
echo The alfa is a regular file and we own it
fi
Inside the shell variables, everything is stored as a string. Nevertheless, these characters can also be only digits and form a number. When we have more than one of them, we can start to make some basic comparisons. The numbers can also be negative; however, only integer numbers are accepted.
Expression
Test checks for what trait?
Arg1 -eq Arg2
True if Arg1 is equal (eq) to Arg2
Arg1 -ne Arg2
True if Arg1 is not equal (ne) to Arg2
Arg1 -lt Arg2
True if Arg1 is less than (lt) Arg2
Arg1 -le Arg2
True if Arg1 is less than or equal (le) to Arg2
Arg1 -gt Arg2
True if Arg1 is greater than (gt) Arg2
Arg1 -ge Arg2
True if Arg1 is greater than or equal (ge) to Arg2
The argument can be also beside the number for the -l string special expression when the length of the string will replace this. Running a test will also save the result of the test into the $? special variable. Here are a couple of instances of this case: