The test command is used to check conditional logic and perform comparisons. You can use the test command in your shell scripts to validate the status of files and perform relevant tasks. It evaluates a conditional expression or logical operation and displays an exit status. The exit status is 0 if the expression is true and 1 if the expression is false.
For example:
var=/etc if test -d $var; then echo "The $var directory exists!" fi
This example uses the -d option to test if a directory exists. There are many such conditional options you can use. Consult the man page for the test command to see them all.
If you encounter the below error while running the test command:
test: command not found
you may try installing the below package as per your choice of distribution:
Distribution | Command |
---|---|
OS X | brew install coreutils |
Debian | apt-get install coreutils |
Ubuntu | apt-get install coreutils |
Alpine | apk add coreutils |
Arch Linux | pacman -S coreutils |
Kali Linux | apt-get install coreutils |
CentOS | yum install coreutils |
Fedora | dnf install coreutils |
Raspbian | apt-get install coreutils |
test Command Examples
1. Test if a given variable is equal to a given string:
# test "$MY_VAR" == "/bin/zsh"
2. Test if a given variable is empty:
# test -z "$GIT_BRANCH"
3. Test if a file exists:
# test -f "path/to/file_or_directory"
4. Test if a directory does not exist:
# test ! -d "path/to/directory"
5. If A is true, then do B, or C in the case of an error (notice that C may run even if A fails):
# test condition && echo "true" || echo "false"