← Back to Bash Course | Chapter 7: String Manipulation | Lesson 2 of 10

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:

  1. The test Command
Syntax
bash
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

bash
#!/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
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
  1. Forgetting the spaces around brackets, as in [$a -eq 1], which is an error.
  2. Leaving variables unquoted in tests, so an empty value gives unary operator expected.
  3. Using == and = inconsistently in [ ], since = is the portable one.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.