test - Linux


Overview

The test command in Linux is used to evaluate conditional expressions and determine whether they are true or false. This utility is primarily useful in scripting, where it helps in decision-making processes. The test command can check file types, compare values, and perform logical operations, making it a backbone tool for shell scripting and automation.

Syntax

The basic syntax of the test command is as follows:

test EXPRESSION
[ EXPRESSION ]
  • EXPRESSION is what you want to evaluate, which can be a file, a string, or a numeric comparison.

Note: The square brackets ([ ]) are synonymous with test, but a space is required between the brackets and the expression.

Options/Flags

File Testing

  • -d FILE: Returns true if FILE exists and is a directory.
  • -e FILE: Returns true if FILE exists.
  • -f FILE: Returns true if FILE exists and is a regular file.
  • -r FILE: Returns true if FILE is readable by you.
  • -w FILE: Returns true if FILE is writable by you.
  • -x FILE: Returns true if FILE is executable by you.

String Testing

  • -z STRING: Returns true if STRING is empty.
  • -n STRING: Returns true if STRING is not empty (this is the default and often omitted).

Arithmetic Testing

  • -eq: Returns true if two numbers are equal.
  • -ne: Returns true if two numbers are not equal.
  • -gt: Returns true if the first number is greater than the second.
  • -lt: Returns true if the first number is less than the second.
  • -ge: Returns true if the first number is greater than or equal to the second.
  • -le: Returns true if the first number is less than or equal to the second.

Logical Operators

  • !: Logical NOT
  • -a: Logical AND
  • -o: Logical OR

Examples

Check if a file exists:

if [ -e /path/to/file.txt ]; then
  echo "File exists."
else
  echo "File does not exist."
fi

Compare two numbers:

if [ $1 -gt $2 ]; then
  echo "$1 is greater than $2."
else
  echo "$1 is not greater than $2."
fi

Check multiple conditions:

if [ -f /path/to/file.txt -a -w /path/to/file.txt ]; then
  echo "File exists and is writable."
fi

Common Issues

  • Spacing: Failing to put spaces between [, ] and the expression can lead to syntax errors.
  • Quoting: Not properly quoting strings within the expression may cause unexpected behavior, especially if the strings contain spaces or special characters.

Integration

The test command can be effectively combined with loops and other commands in a script:

Loop through files and check if writable:

for file in /some/directory/*; do
  if [ -w "$file" ]; then
    echo "$file is writable"
  fi
done
  • [[ ... ]]: An advanced version of test used in bash for more complex expressions.
  • expr: Expression evaluation tool used for arithmetic and string operations in shell scripts.

Further reading and resources can be found in the GNU coreutils test manual.