Test command in Linux and Unix with examples

About Test

Test command allows us to check file types and even compare values.
It exits with the status which is determined by EXPRESSION. We can see the exit status of the command prompt, by using echo “$?” Test command is a little bit different because when it returns true, then it will return 0 and if the statement is false it will return non zero value.

SYNOPSIS

test EXPRESSION
test

[ EXPRESSION ]
[ ]
[ OPTION

Examples

1.) This example will test if the file named “newfile1” is a file. If it is, then it will echo True

[[email protected] ~]$ test -f newfile1 && echo "True"
True

2.) This example will test if the file named “newfile1” is writable by my user. If it is, then it will echo True

[[email protected] ~]$ test -w newfile1 && echo "True"
True

3.) In this example we are checking whether 1 is greater than 2 if it is, then return true otherwise return false

[[email protected] ~]$ test 1 -gt 2 && echo "True" || echo "False"
False

4.) This command will test if 5 is equal to 5. If it is, then it will return 0 or non 0 value if it is false

[[email protected] ~]$ [ 5 -eq 5 ]; echo $?
0

So that was a quick tutorial on the linux “Test” command. Have any questions ? Leave a comment below.

Add Comment