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 true1โ 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]
| Option | Meaning |
|---|---|
-f file | File exists and is a regular file |
-d dir | Directory exists |
-e file | File exists (any type) |
-r file | File has read permission |
-w file | File has write permission |
-x file | File has execute permission |
-s file | File exists and not empty |
Example
if [ -f a.sh ]; then
echo "File exists"
fi
🔢 Integer (number) tests
| Option | Meaning |
|---|---|
-eq | equal |
-ne | not equal |
-gt | greater than |
-lt | less than |
-ge | greater or equal |
-le | less or equal |
Example
a=10
b=20
if [ $a -lt $b ]; then
echo "a is smaller"
fi
🔤 String tests
| Option | Meaning |
|---|---|
= | strings are equal |
!= | strings not equal |
-z str | string is empty |
-n str | string is not empty |
Example
name="Linux"
if [ "$name" = "Linux" ]; then
echo "Correct OS"
fi
🔗 Logical operators
| Operator | Meaning |
|---|---|
-a | AND |
-o | OR |
! | NOT |
Example
if [ -f a.sh -a -r a.sh ]; then
echo "Readable file"
fi
🆚 test vs [ ] vs [[ ]]
| Form | Usage |
|---|---|
test | Old, 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”