The command test in the shell is used to check whether a condition is true. It can test numbers, strings and files.
Number arguments test
Tag | Description |
---|---|
-eq | Integer1 and Integer2 variables are algebraically equal |
-ne | Integer1 and Integer2 variables are not algebraically equal |
-gt | Integer1 is greater than Integer2 |
-ge | Integer1 is greater than or equal to Integer2 |
-lt | Integer1 is lower than Integer2 |
-le | Integer1 is lower than or equal to Integer2 |
For example
num1=100
num2=100
if test $[num1] -eq $[num2]
then
echo 'number 1 is equal to number 2!'
else
echo 'number 1 is not equal to number 2!'
fi
Output is
number 1 is equal to number 2!
[] In the code performs basic arithmetic operations, such as:
#!/bin/bash
a=15
b=14
result=$[a+b] # Note that there can be no spaces on both sides of the equal sign
echo "result is: $result"
Output is
result is: 29
String arguments test
Tag | Description |
---|---|
= | String1 and String2 variables are equal |
!= | String1 and String1 variables are not equal |
-z string | Check the length of the string is zero |
-n string | Check the length of the string is not zero |
For example
num1="linuxcommands"
num2="linuxcommands.site"
if test $num1 = $num2
then
echo 'String1 and String2 variables are equal !'
else
echo 'String1 and String2 variables are not equal!'
fi
Output is
String1 and String2 variables are not equal!
File arguments test
Tag | Description |
---|---|
-e FILE | FILE exists |
-r FILE | FILE exists and read permission is granted |
-w FILE | FILE exists and write permission is granted |
-x FILE | FILE exists and execute permission is granted |
-s FILE | FILE exists and has a size greater than zero |
-d FILE | FILE exists and is a directory |
-f FILE | FILE exists and is a regular file |
-c FILE | FILE exists and is character special |
-b FILE | FILE exists and is block special |
For example
cd /bin
if test -e ./bash
then
echo 'FILE exists!'
else
echo 'FILE does not exist!'
fi
Output is
FILE does not exist!
In addition, shell also provides three logical operators (-a), or (-o), and not (!) which be used to connect the test conditions, and its priority is: “!” is the highest, “-a” is the second, “-o” is the lowest.
cd /bin
if test -e ./notFile -o -e ./bash
then
echo 'At least one file exists!'
else
echo 'Two files exist'
fi
Output is
At least one file exists!