test Command Examples in Linux

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.

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"
Related Post