Magazine

Use the Test Command in Linux

Posted on the 12 April 2021 by Satish Kumar @satish_kumar86

Let’s now understand the test command.

Using the test command

Let’s look at the following example to check the content or value of expressions:

$ test $name=Ganesh
$ echo $?0 if success and 1 if failure.

In the preceding example, we want to check whether the content of the variable name is the same asGaneshand?. To check this, we have used thetestcommand. Thetestcommand will store the result of the comparison in the?variable.

We can use the following syntax for the precedingtestcommand. In this case, we used[ ]instead of thetestcommand. We’ve enclosed the expression to be evaluated in square brackets:

$ [[ $name = Ganesh ]]      # Brackets replace the test command
$ echo $?0

During the evaluation of expressions by test, we can even use wildcard expressions:

$ [[ $name = [Gg]????? ]]
$ echo $?0

Therefore, we can either use the test command or square brackets for checking or evaluating expressions. Since word splitting will be performed on variables, if we are using text with white spaces, then we will need to enclose the text inside double quotes, " "

Using the test command with double brackets

Let’s consider a case where we want to check whether there is the name Ganesh and whether his friend is John. In this case, we will have multiple expressions to be checked using the AND operator, &. In such a case, we can use the following syntax:

$ [[ $name == Ganesh & $friend == "John" ]]

Another way to do this is as follows:

[ $name == Ganesh ] & [ $friend == "John" ]

We used double brackets in the preceding expressions.

Here, we want to evaluate multiple expressions on the same command line. We can use the preceding syntax withAND(&) orOR(||) logical operators.

String comparison options for the test command

The following is a summary of various options for string comparison using test, which is taken from the Bash reference manual available at http://www.gnu.org/software/bash/:

Test operator

Tests true if

-n string

True if the length of string is non-zero.

-z string

True if the length of string is zero.

string1 != string2

True if the strings are not equal.

string1 == string2

string1 = string2

True if the strings are equal.

string1 > string2

True ifstring1sorts afterstring2lexicographically.

string1 < string2

True ifstring1sorts beforestring2lexicographically.

If we want to check whether the length of a string is non-zero, then we can check it as follows:

test -n $string      or     [ -n $string ]echo $?

If the result is0, then we can conclude that the string length is non-zero. If the content of?is non-zero, then the string is 0 in length.

Let’s write a shell script,test01.sh, for learning various string operations:

test01.sh
#!/bin/bash 
 
str1="Ganesh" 
str2="Mumbai"; 
str3= 
 
[ $str1 = $str2 ] # Will Check Two Strings Are Equal Or Not 
echo $? 
 
[ $str1 != $str2 ] # Will Check Two Strings Are Not Equal 
echo $? 
 
[ -n $str1 ] # Will confirm string length is greater than zero 
echo $? 
 
[ -z $str3 ] # Will Confirm length of String is Zero 
echo $?

Let’s test the following program:

$ chmod +x test01.sh
$ ./test01.sh

The following will be the output after executing the preceding commands:

Output:
1000

Let’s write an interactive shell script, test02.sh, to get names from the user and then compare whether both are the same:

test02.sh
#!/bin/bash 
echo "Enter First name" 
read name1 
echo "Enter Second name" 
read name2 
[ $name1 = $name2 ] # Check equality of two names 
echo $? 
[ -n  $name2 ] # Check String Length is greater than Zero 
echo $?

Let’s test the following program:

$ chmod +x test02.sh
$ ./test02.sh

The following will be the output after executing the preceding commands:

Output:
Enter First nameLEVANA
Enter Second nameTECHNOLOGIES
10

Numerical comparison operators for the test command

The following is the summary of various options for numerical comparison using test:

Test Operator

Tests True If

[ integer_1 -eq integer_2 ]

integer_1is equal tointeger_2

[integer_1 -ne integer_2 ]

integer_1is not equal tointeger_2

[integer_1 -gt integer_2 ]

integer_1is greater thaninteger_2

[integer_1 -ge integer_2 ]

integer_1is greater than or equal tointeger_2

[integer_1 -ge integer_2 ]

integer_1is less thaninteger_2.

[integer_1 -le integer_2 ]

integer_1is less than or equal tointeger_2

Let’s write the shell script, test03.sh, for learning the various numerical test operators’ usage:

test03.sh
#!/bin/bash 
 
num1=10 
num2=30 
 
echo $(($num1 < $num2))  # compare for less than 
[ $num1 -lt $num2 ]      # compare for less than 
echo $? 
[ $num1 -ne $num2 ]      # compare for not equal 
echo $? 
[ $num1 -eq $num2 ]      # compare for equal to 
echo $?

Let’s test the following program:

$ chmod +x test03.sh\
$ ./test03.sh

The following will be the output after executing the preceding commands:

Output:
1000

Let’s write the script, test04.sh, for interactively asking the user for three numbers and then testing those numbers for various comparisons:

test04.sh
#!/bin/bash 
echo "Please enter 1st First Number" 
read num1 
echo "Please enter 2nd Number" 
read num2 
echo "Please enter 3rd Number" 
read num3 
[[ $num1 > $num2 ]]  # compare for greater than 
echo $? 
[[ $num1 != $num2 ]] # compare for not equal to 
echo $? 
[[ $num2 == $num3 ]] # compare for equal to 
echo $? 
[[ $num1 & $num2 ]] # Logical And Operation 
echo $? 
[[ $num2 || $num3 ]] # Logical OR Operation 
echo $?

Let’s test the following program:

$ chmod +x test04.sh
$ ./test04.sh

The following will be the output after executing the preceding commands:

Output:
Please enter 1st First Number10
Please enter 2nd Number20
Please enter 3rd Number3010100

Let’s write the script test05.sh for using string and numerical test operations:

test05.sh
#!/bin/bash 
Var1=20 
Var2=30 
Str1="Accenture" 
FileName="TestStringOperator" 
 
test $Var1 -lt $Var2  # Test for Less Than 
echo $? 
test $Var1 -gt $Var2  # Test For Greater Than 
echo $? 
test -n $Str1         # Test for String Having Length Greater Than 0 
echo $? 
test -f $FileName     # Test for File Attributes 
echo $?

Let’s test the following program:

$ chmod +x test05.sh
$ ./test05.sh

The following will be the output after executing the preceding commands:

Output:
0101

We used the test operation for the file in this script. It will check whether the file is present. You will learn more about it in the following section.

Now we will write the scripttest06.shusing the test command interactively, ask the user for data, and then perform numerical, as well as string comparison, operations:

test06.sh
#!/bin/bash 
echo "Please enter 1st Number" 
read num1 
echo "Please enter 2nd Number" 
read num2 
echo 
test $num1 -eq $num2    # Test for Equal 
echo $? 
test $num1 -ne $num2    # Test for Not Equal 
echo $? 
test $num1 -ge $num2    # Test for Greater Than Equal 
echo $? 
 
echo "Please enter 1st String" 
read Str1 
echo "Please enter 2nd String" 
read Str2 
 
test $Str1 = $Str2    # Test for Two Strings Are Equal 
echo $? 
test -z $Str1        # Test for The Length Of The String Is > 0 
echo $? 
test $Str2        # Test for The String Is Not NULL 
echo $?

Let’s test the following program:

$ chmod +x test06.sh
$ ./test06.sh

The following will be the output after executing the preceding commands:

Output:
Please enter 1st Number10
Please enter 2nd Number20101
Please enter 1st StringLEVANA
Please enter 2nd StringTECHNOLOGIES110

Depending on the value of $? in the preceding output, we can decide whether the operation returned true or false. We will use this in ifcase, and similar decision-making, as well as in looping, activities.

File test options for the test command

The following arethevarious options for file-handling operations using the test command:

-c file_name

Check whether file is character special file

-d file_name

Check whether directory exists

-e file_name

Check whether file exists

-f file_name

Check whether file is a regular file and not a directory

-G file_name

Check whether file exists and is owned by the effective group ID

-g file_name

Check whether file hasSet-group-IDset

-k file_name

Check whether file hasStickybit set

-L file_name

Check whether file is symbolic link

-p file_name

Check whether file is a named pipe

-O file_name

Check whether file exists and is owned by the effective user ID

-r file_name

Check whether file is readable

-S file_name

Check whether file is a socket

-s file_name

Check whether the file has non-zero size

-t file_name

Check whether the file hasfd(file descriptor) and is open in a terminal

-u file_name

Check whether the file hasSet-user-IDbit set

File-testing binary operators

The following are various options for binary file operations using test, which is taken from the Bash reference manual available at http://www.gnu.org/software/bash/:

Test Operator

Tests True If

[ file_1 -nt file_2 ]

Check whetherfile_1is newer thanfile_2

[ file_1 -otfile_2 ]

Check whetherfile_1is older thanfile_2

[ file_1 -ef file_2 ]

Check whetherfile_1andfile_2have the same device orinodenumbers

Let’s write the script test07.sh to test the basic file attributes, such as whether it is a file or folder and whether it has a file size bigger than 0. The output will be different depending on whether the case file is present:

test07.sh
#!/bin/bash 
# Check whether file is Directory 
[ -d work ] 
echo $? 
# Check that is it a File 
[ -f test.txt ] 
echo $? 
# Check whether File has size greater than 0 
[ -s test.txt ] 
echo $? 

Let us test the program:

$ chmod +x test07.sh
$ ./test07.sh

The following will be the output after executing the preceding commands:

111
$ mkdir work
$ touch test.txt
$ ./test07.sh001

We executed the script with and without the directory andtext.txtfile.

The following script,test08.sh, is checking the file permissions such as read, write, and execute permissions:

test08.sh
#!/bin/bash 
# Check whether File has Read Permission 
[ -r File2 ] 
echo $? 
# Check whether File Has Write Permission 
[ -w File2 ] 
echo $? 
# Check whether File Has Execute Permission 
[ -x File2 ] 
echo $?

Let’s test the program:

$ touch File2
$ ls -l File2-rw-rw-r-- 1 student student    0 Jun 23 22:37 File2
$ chmod +x test08.sh
$ ./test08.sh

The following will be the output after executing the preceding commands:

Output:
001

Logical test operators

The following are the various options for logical operations using test, which is taken from the Bash reference manual available at http://www.gnu.org/software/bash/:

Test Operator

Tests True If

[ string_1 -a string_1 ]

Bothstring_1andstring_2are true

[ string_1 -o string_2 ]

Eitherstring_1orstring_2is true

[ ! string_1 ]

Not astring_1match

[[ pattern_1 & pattern_2 ]]

Bothpattern_1andpattern_2are true

[[ pattern_1 || pattern_2 ]]

Eitherpattern_1orpattern_2is true

[[ ! pattern ]]

Not a pattern match

We can use the test operator for strings along with pattern matching as follows:

$ name=Ganesh 
$ [[ $name == [Gg]anesh ]]      # Wildcards allowed 
$ echo $? 
0

The following is an example for multiple strings with the & logical operator:

$ name=Ganesh; friend=Anil 
$ [[ $name == [Gg]anesh & $friend == "Lydia" ]] 
$ echo $? 
1

The following is the script with the test command along with the extended pattern matching enabled:

$ shopt -s extglob     # we are enabling extended pattern matching 
$ city=Kannur 
$ [[ $city == [Kk]a+(n)ur ]] 
$ echo $? 
0

In the given expressions, we are checking the equality of strings. It tests whether the city name starts with K or k, followed by a, one or more n characters, u, and r


Back to Featured Articles on Logo Paperblog