Shell Command Test

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

TagDescription
-eqInteger1 and Integer2 variables are algebraically equal
-neInteger1 and Integer2 variables are not algebraically equal
-gtInteger1 is greater than Integer2
-geInteger1 is greater than or equal to Integer2
-ltInteger1 is lower than Integer2
-leInteger1 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

TagDescription
=String1 and String2 variables are equal
!=String1 and String1 variables are not equal
-z stringCheck the length of the string is zero
-n stringCheck 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

TagDescription
-e FILEFILE exists
-r FILEFILE exists and read permission is granted
-w FILEFILE exists and write permission is granted
-x FILEFILE exists and execute permission is granted
-s FILEFILE exists and has a size greater than zero
-d FILEFILE exists and is a directory
-f FILEFILE exists and is a regular file
-c FILEFILE exists and is character special
-b FILEFILE 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!

Add a Comment

Your email address will not be published. Required fields are marked *