Overview
The test command evaluates a given expression and returns an exit status of 0 if the result is true, and 1 if it is false. It is primarily used for conditional execution in shell scripts, such as within `if` and `while` statements. The `[` command is an alternative form of the `test` command, and `[[` provides extended functionality in Bash/Ksh/Zsh.
Key Features
- Check file types and attributes
- Compare string values
- Compare integer values
- Logical operations (AND, OR, NOT)
Key Options
The test command uses various unary and binary operators to evaluate conditional expressions.
File Attribute Checks
String Comparison
Integer Comparison
Logical Operators
Generated command:
Try combining the commands.
Description:
`test` Executes the command.
Combine the above options to virtually execute commands with AI.
Usage Examples
Various examples of evaluating conditional expressions using the test command.
Check File Existence
if test -e /etc/passwd; then echo "/etc/passwd file exists."; fi
Checks if the `/etc/passwd` file exists.
Check if it's a Directory
if test -d /tmp; then echo "/tmp is a directory."; fi
Checks if `/tmp` is a directory.
String Comparison
MY_VAR="hello"
if test "$MY_VAR" = "hello"; then echo "The variable value is hello."; fi
Checks if the variable `MY_VAR` is equal to 'hello'.
Integer Comparison
COUNT=15
if test "$COUNT" -gt 10; then echo "COUNT is greater than 10."; fi
Checks if the variable `COUNT` is greater than 10.
Logical AND Operation
touch file.txt
if test -f file.txt -a -s file.txt; then echo "file.txt exists and is not empty."; fi
rm file.txt
Checks if `file.txt` exists and is not empty.
Using `[` instead of `test`
if [ -f /etc/hosts ]; then echo "/etc/hosts file exists."; fi
The `test` command can be replaced with `[`. Remember to close it with `]`.
Tips & Precautions
Useful tips and points to be aware of when using the test command.
Key Tips
- The `[` command is identical to the `test` command and must be closed with `]`. Both `[` and `]` are treated as separate arguments, so they require spaces around them.
- The `[[` command is supported only in Bash, Ksh, and Zsh, and offers more powerful features (like regular expressions and better handling of spaces). Inside `[[`, variables do not need to be quoted to be safe.
- It is always safer to quote variables when using them (e.g., `test "$VAR" = "value"`). This prevents errors that can occur if the variable is empty or contains spaces.
- Use `-eq`, `-ne`, `-gt`, `-lt`, `-ge`, `-le` for integer comparisons, and `=`, `!=`, `-z`, `-n` for string comparisons. Mixing them can lead to unexpected results.