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:
#Bash/Ksh unset -v suffix fileCnt [[ $1 == -p ]] && suffix=png if [[ -d ${HOME}/images ]]; then cd "$HOME"/images else echo 'Image directory not found. Exiting.' >&2 exit 1 fi for file in *.gif; do if [[ -f $file ]]; then if mv "$file" "${file%gif}${suffix:-jpg}"; then ((fileCnt++)) else printf 'Failed to move: %s\n' "$file" >&2 fi fi done printf 'Finished moving %d files.\n' "$fileCnt" >&2
Links
Tests and Conditionals in the BashGuide.
BashFAQ/031 - What is the difference between test, [, and [[ ?
The classic test command and test expresssion on Bash Hackers.
Bash Conditional Expressions in the Bash infopages.