Test expressions

A test is a predicate which can perform various logical operations on strings, patterns, filenames, and arithmetic. Tests are an important part of the shell language. Almost every practical shell script includes at least a few test expressions. There are two types of tests: the test simple command ([ or test), and the test expression compound command ([[ ... ]]).

The [ command is the most common form of test, and is nearly identical to the test command. [ and test are specified by POSIX and are the portable types of test that should be used in scripts requiring POSIX conformance.

The [[ (test expresssion) compound command is a more powerful type of test introduced by AT&T ksh88, and later adopted by all other kshes (ksh93, mksh, pdksh, etc), Bash, and Zsh. While [[ is relatively portable and consistent where implemented, it is not specified by POSIX. Minimal shells like Dash don't support it.

When writing shell scripts, we recommend consistently using either [[ when targeting Bash and other Ksh-like shells that don't require POSIX conformance, or [, only when POSIX conformance is required, in scripts that use only POSIX features exclusively.

This example shows typical test expression usage:


unset -v suffix fileCnt
[[ $1 == -p ]] && suffix=png

if [[ -d ${HOME}/images ]]; then
    cd "$HOME"/images
    echo 'Image directory not found. Exiting.' >&2
    exit 1

for file in *.gif; do
    if [[ -f $file ]]; then
        if mv "$file" "${file%gif}${suffix:-jpg}"; then
            printf 'Failed to move: %s\n' "$file" >&2

printf 'Finished moving %d files.\n' "$fileCnt" >&2

tests (last edited 2012-10-30 22:43:49 by ormaaj)