Test Command in Linux



Test command is used to check the condition is true or not. To test a condition use test or [ ] as explained below.

Syntax of test command


if test condition
then
statement
fi


or

if [ condition ]
then
statement
fi


Note that you must put space between braces [ ] to test a condition.


Test condition Linux


Test Condition Types


1.   Arithmetic Comparison


−eq
Equal to
−ne
Not equal to
−gt
Greater than
−ge
Greater than or equal
−lt
Less than
−le
Less than or equal
!
not

Example:

i=10
J=15
if [ i –eq j ]
then
echo “ i is equal to j”
else
echo “ i is not equal to j”
fi


Here we assign two integer variables i and j and the condition if both are equal or not using -eq.

2. String Comparison


string1 = string2
the strings are equal.
string1 != string2
the strings are not equal
−n string
string is not null
−z string
the string is null

Example:

var1=Linux
var2=Linux
if [ var1 = var2 ]
then
echo “ var1 and var2 strings are equal”
else
echo “ var1 and var2 strings are not equal”
fi


Here we define two string variable and test the condition if they are equal or not.

3. File Comparison


-d
directory
-e
file exist
-f
Regular file
-g
SGID is set on file
-r
Readable file
-s
File is not zero in size
-u
SUID is set on file
-w
Writable file
-x
Executable file

Example:

if [ -f file.txt ]
then
echo “file.txt is a regular file”
fi



 Here we test the type of file file.txt, is it regular file or directory or other.


No comments: