More Bash answers

by Danny
Published 2 min read

Use the test operators -e, -f and -d inside [[ ]] to check whether a path exists, is a regular file or is a directory, and avoid the common quoting traps.

The short answer

#

Use a test expression with the right operator: -f for a regular file, -d for a directory, and -e for anything at all. In Bash, prefer the double-bracket form, and quote the path.


_10
if [[ -f "$config" ]]; then
_10
echo "Found config file"
_10
fi
_10
_10
if [[ ! -d "$out_dir" ]]; then
_10
mkdir -p "$out_dir"
_10
fi

Why it happens

#

The shell has no "exists" function. Instead, it has the test command, which checks a condition and sets an exit status: 0 for true, 1 for false. if runs its body when the command exits with 0.

There are three ways to write the same test:


_10
test -f "$path" # the original command
_10
[ -f "$path" ] # the same command under another name; needs the closing ]
_10
[[ -f "$path" ]] # Bash keyword with safer parsing

[ is an ordinary command, so its arguments go through word splitting and glob expansion. An unquoted empty variable or a path with spaces turns into the wrong number of arguments and gives errors such as "unary operator expected" or "too many arguments". [[ is part of Bash's syntax, so variables inside it are not split. It also supports &&, || and pattern matching. Use [ only when you need the script to run under plain sh.

How to fix it

#

Pick the right operator

OperatorTrue when the path
-eexists, whatever it is
-fis a regular file
-dis a directory
-L or -his a symbolic link
-sexists and is not empty
-ris readable by you
-wis writable by you
-xis executable, or for a directory, can be entered

-f and -d follow symbolic links, so a link to a directory passes -d. A broken link, one whose target is missing, fails -e, -f and -d but passes -L.

Negate and combine


_10
if [[ ! -e "$lock" ]]; then
_10
touch "$lock"
_10
fi
_10
_10
if [[ -f "$src" && -r "$src" ]]; then
_10
cp "$src" "$dest"
_10
fi

Short one-liners

For quick checks, chain with && or ||:


_10
[[ -d "$HOME/.cache" ]] || mkdir -p "$HOME/.cache"
_10
[[ -f .env ]] && source .env

In scripts that use set -e, be careful with the && form as the last line of a function: when the test is false, the function returns a non-zero status.

Fail early with a clear message


_10
if [[ ! -f "$1" ]]; then
_10
echo "Error: file not found: $1" >&2
_10
exit 1
_10
fi

Check whether any file matches a pattern

Tests do not expand globs inside [[, and with [ a pattern that matches several files breaks the test. To ask "are there any .log files?", use compgen or an array:


_10
if compgen -G "logs/*.log" > /dev/null; then
_10
echo "There are log files"
_10
fi
_10
_10
shopt -s nullglob
_10
files=(logs/*.log)
_10
if (( ${#files[@]} > 0 )); then
_10
echo "Found ${#files[@]} log files"
_10
fi

Do not check when you can just act

Checking and then acting leaves a gap where another process can create or remove the file. Often it is simpler to try the action and handle the failure:


_10
mkdir -p "$dir" # no need to check first
_10
cp "$src" "$dest" || { echo "copy failed" >&2; exit 1; }

Common pitfalls

#
  • Leaving out the spaces. [[-f "$x"]] is a syntax error; the brackets need spaces on both sides.
  • Not quoting the variable when using single brackets. [ -f $path ] breaks on spaces and passes when the variable is empty.
  • Using -e when you need a file specifically. A directory with the same name will pass.
  • Writing ~ inside quotes. "~/file" is not expanded; use "$HOME/file".
  • Testing a relative path from the wrong place. Paths are relative to the current directory, not to the script. Use "$(dirname "$0")" or BASH_SOURCE to find files next to the script.
#

Was this resource helpful?