Alternatively, using the more robust [[ ]] instead of [ ] and the more concise but less legible || instead of if-then-else
[[ -d $TEST ]] || mkdir "$TEST"
EDIT: seeing your reply above, better
[[ -e TEST ]] || mkdir TEST
You had to change $TEST to TEST because $TEST means "the value of variable TEST" whereas you want the string TEST.
On reflection it might be worth handling the error condition of TEST existing but not being a directory.
if [[ ! -d TEST ]]; then
if [[ -e TEST ]]; then
echo 'Cannot create directory TEST; TEST already exists:' >&2
/bin/ls -l TEST >&2
mkdir TEST || exit 1
- >&2 means "redirect stdout to stderr". It is conventional and useful to write error messages to stderr. It allows error messages to be easily separated from informational messages. By default both stdout and stderr are displayed on the screen.
- /bin/ls is used instead of ls because ls is commonly aliased and might give unexpected results.
- If mkdir TEST fails it will write an error message to stderr and set its return code to non-zero. The shell, on detecting a non-zero return code, will execute the command after the || thus terminating the script.