0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use test Command in Bash: Syntax and Examples

In bash, the test command evaluates expressions and returns a status code indicating true or false. You use it to check file properties, compare strings or numbers, and combine conditions in scripts. The syntax is test EXPRESSION or the shorthand [ EXPRESSION ].
📐

Syntax

The test command syntax is simple:

  • test EXPRESSION - evaluates the EXPRESSION.
  • [ EXPRESSION ] - a shorthand that requires spaces around brackets.

Common expressions include file checks (e.g., -f filename), string comparisons (e.g., string1 = string2), and numeric comparisons (e.g., num1 -eq num2).

bash
test EXPRESSION
[ EXPRESSION ]
💻

Example

This example checks if a file named example.txt exists and prints a message accordingly.

bash
#!/bin/bash
filename="example.txt"

if test -f "$filename"; then
  echo "$filename exists."
else
  echo "$filename does not exist."
fi

# Using shorthand
if [ -f "$filename" ]; then
  echo "$filename exists (shorthand)."
else
  echo "$filename does not exist (shorthand)."
fi
Output
example.txt does not exist. example.txt does not exist (shorthand).
⚠️

Common Pitfalls

Common mistakes when using test include:

  • Forgetting spaces around brackets in the shorthand form, e.g., [ -f file] is wrong; it must be [ -f file ].
  • Not quoting variables, which can cause errors if variables are empty or contain spaces.
  • Using == for string comparison in test (single = is standard).
bash
# Wrong: missing spaces
if [ -f "$filename" ] ; then echo "Exists"; fi

# Right: spaces included
if [ -f "$filename" ] ; then echo "Exists"; fi

# Wrong: unquoted variable
if [ -f $filename ] ; then echo "Exists"; fi

# Right: quoted variable
if [ -f "$filename" ] ; then echo "Exists"; fi
📊

Quick Reference

ExpressionMeaning
-f filenameTrue if filename exists and is a regular file
-d dirnameTrue if dirname exists and is a directory
string1 = string2True if strings are equal
string1 != string2True if strings are not equal
-z stringTrue if string is empty
num1 -eq num2True if numbers are equal
num1 -gt num2True if num1 is greater than num2
! EXPRESSIONTrue if EXPRESSION is false
EXPR1 -a EXPR2True if both EXPR1 and EXPR2 are true
EXPR1 -o EXPR2True if either EXPR1 or EXPR2 is true

Key Takeaways

Use test or [ ] to evaluate conditions in bash scripts.
Always include spaces around brackets and quote variables to avoid errors.
Use -f, -d, and other flags to check file types.
Use single = for string comparison inside test.
Combine conditions with -a (and), -o (or), and negate with !.