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:

   1 #Bash/Ksh
   2 
   3 unset -v suffix fileCnt
   4 [[ $1 == -p ]] && suffix=png
   5 
   6 if [[ -d ${HOME}/images ]]; then
   7     cd "$HOME"/images
   8 else
   9     echo 'Image directory not found. Exiting.' >&2
  10     exit 1
  11 fi
  12 
  13 for file in *.gif; do
  14     if [[ -f $file ]]; then
  15         if mv -- "$file" "${file%gif}${suffix:-jpg}"; then
  16             ((fileCnt++))
  17         else
  18             printf 'Failed to move: %s\n' "$file" >&2
  19         fi
  20     fi
  21 done
  22 
  23 printf 'Finished moving %d files.\n' "$fileCnt" >&2

tests (last edited 2024-05-02 20:47:37 by emanuele6)