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

The test Command

In this page:

  1. The test Command

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

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.