The test Command
The test command is like a yes-or-no quiz question for the computer, such as 'is this file there?'. It answers by quietly saying pass or fail, and the script uses that to decide what to do.
In this page:
Syntax
test expression
[ expression ]
The test Command
test expression (also written as [ expression ]) evaluates a condition and sets its exit status accordingly, forming the classic POSIX way of writing conditions.
[ ] requires spaces around every token and around the brackets themselves. It predates the more feature-rich [[ ]] and is still used for POSIX-portable scripts.
Warning:
Missing a space, like
[$a -eq $b], is a syntax error — [ is actually a command that needs spaces as argument separators.Example: The test Command
#!/bin/bash
a=5
if test "$a" -eq 5; then
echo "a equals 5 (using test)"
fi
if [ "$a" -eq 5 ]; then
echo "a equals 5 (using [ ])"
fi
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting the spaces around brackets, as in
[$a -eq 1], which is an error. - Leaving variables unquoted in tests, so an empty value gives
unary operator expected. - Using
==and=inconsistently in[ ], since=is the portable one.
🔒
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: