What is test command?

The test command is used to check conditions and return true or false.
Itโ€™s mainly used in shell scripts and if statements.

👉 It does not print output
👉 It sets an exit status

  • 0 โ†’ condition is true
  • 1 โ†’ condition is false

🔹 Syntax

test condition

OR (more commonly)

[ condition ]

⚠️ Important:

  • There must be spaces after [ and before ]

✅ Correct:

[ -f file.txt ]

❌ Wrong:

[-f file.txt]
OptionMeaning
-f fileFile exists and is a regular file
-d dirDirectory exists
-e fileFile exists (any type)
-r fileFile has read permission
-w fileFile has write permission
-x fileFile has execute permission
-s fileFile exists and not empty

Example

if [ -f a.sh ]; then
    echo "File exists"
fi

🔢 Integer (number) tests

OptionMeaning
-eqequal
-nenot equal
-gtgreater than
-ltless than
-gegreater or equal
-leless or equal

Example

a=10
b=20

if [ $a -lt $b ]; then
    echo "a is smaller"
fi

🔤 String tests

OptionMeaning
=strings are equal
!=strings not equal
-z strstring is empty
-n strstring is not empty

Example

name="Linux"

if [ "$name" = "Linux" ]; then
    echo "Correct OS"
fi

🔗 Logical operators

OperatorMeaning
-aAND
-oOR
!NOT

Example

if [ -f a.sh -a -r a.sh ]; then
    echo "Readable file"
fi

🆚 test vs [ ] vs [[ ]]

FormUsage
testOld, POSIX standard
[ ]Same as test, most common
[[ ]]Bash advanced (recommended)

Example

[[ $a -gt 5 && $b -lt 50 ]]

💡 Quick real-life example

#!/bin/bash

if [ -d /home ]; then
    echo "Home directory exists"
else
    echo "No home directory"
fi

⚠️ Common mistakes

❌ Missing spaces

[ $a -eq 10]

❌ Using = for numbers

[ $a = 10 ]   # wrong for integers

✅ 1. Check whether a file exists

if [ -e file.txt ]; then
    echo "File exists"
else
    echo "File not found"
fi

✅ 2. Check whether a file is a directory

if [ -d /home ]; then
    echo "It is a directory"
fi

✅ 3. Check whether a file is empty

if [ -s data.txt ]; then
    echo "File is not empty"
else
    echo "File is empty"
fi

✅ 4. Check read permission of a file

if [ -r a.sh ]; then
    echo "Read permission granted"
else
    echo "Read permission denied"
fi

✅ 5. Compare two numbers

a=15
b=10

if [ $a -gt $b ]; then
    echo "a is greater than b"
fi

✅ 6. Check whether a number is zero or not

num=0

if [ $num -eq 0 ]; then
    echo "Number is zero"
else
    echo "Number is not zero"
fi

✅ 7. Check whether a string is empty

name=""

if [ -z "$name" ]; then
    echo "String is empty"
fi

✅ 8. Compare two strings

os="Linux"

if [ "$os" = "Linux" ]; then
    echo "Correct OS"
fi

✅ 9. Check file existence AND execute permission

if [ -f run.sh -a -x run.sh ]; then
    echo "Executable file exists"
fi

✅ 10. Check whether a user entered argument

if [ -n "$1" ]; then
    echo "Argument provided"
else
    echo "No argument given"
fi

test command

[ -f a.txt ] && echo “File exists”

By admin

Leave a Reply

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