Shell test Command
The test command in Shell is used to check if a certain condition is true. It can perform tests on numbers, strings, and files.
Numerical Tests
| Parameter | Description |
|---|---|
| -eq | True if equal |
| -ne | True if not equal |
| -gt | True if greater than |
| -ge | True if greater than or equal |
| -lt | True if less than |
| -le | True if less than or equal |
Example
num1=100
num2=100
if test $[num1] -eq $[num2]
then
echo 'The two numbers are equal!'
else
echo 'The two numbers are not equal!'
fi
Output:
The two numbers are equal!
The [] in the code performs basic arithmetic operations, such as:
Example
#!/bin/bash
a=5
b=6
result=$[a+b] # Note that there must be no spaces around the equal sign
echo "result is: $result"
Output:
result is: 11
String Tests
| Parameter | Description |
|---|---|
| = | True if equal |
| != | True if not equal |
| -z string | True if the length of the string is zero |
| -n string | True if the length of the string is non-zero |
Example
num1="ru1noob"
num2="tutorialpro"
if test $num1 = $num2
then
echo 'The two strings are equal!'
else
echo 'The two strings are not equal!'
fi
Output:
The two strings are not equal!
File Tests
| Parameter | Description |
|---|---|
| -e filename | True if the file exists |
| -r filename | True if the file exists and is readable |
| -w filename | True if the file exists and is writable |
| -x filename | True if the file exists and is executable |
| -s filename | True if the file exists and has a size greater than zero |
| -d filename | True if the file exists and is a directory |
| -f filename | True if the file exists and is a regular file |
| -c filename | True if the file exists and is a character special file |
| -b filename | True if the file exists and is a block special file |
Example
cd /bin
if test -e ./bash
then
echo 'The file exists!'
else
echo 'The file does not exist!'
fi
Output:
The file exists!
Additionally, Shell provides the logical operators AND (-a), OR (-o), and NOT (!) for connecting test conditions, with the precedence being: ! highest, -a next, and -o lowest. For example:
Example
cd /bin
if test -e ./notFile -o -e ./bash
then
echo 'At least one file exists!'
else
echo 'Neither file exists'
fi
Output:
At least one file exists!