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.
_10if [[ -f "$config" ]]; then_10 echo "Found config file"_10fi_10_10if [[ ! -d "$out_dir" ]]; then_10 mkdir -p "$out_dir"_10fi
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:
_10test -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
| Operator | True when the path |
|---|---|
-e | exists, whatever it is |
-f | is a regular file |
-d | is a directory |
-L or -h | is a symbolic link |
-s | exists and is not empty |
-r | is readable by you |
-w | is writable by you |
-x | is 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
_10if [[ ! -e "$lock" ]]; then_10 touch "$lock"_10fi_10_10if [[ -f "$src" && -r "$src" ]]; then_10 cp "$src" "$dest"_10fi
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
_10if [[ ! -f "$1" ]]; then_10 echo "Error: file not found: $1" >&2_10 exit 1_10fi
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:
_10if compgen -G "logs/*.log" > /dev/null; then_10 echo "There are log files"_10fi_10_10shopt -s nullglob_10files=(logs/*.log)_10if (( ${#files[@]} > 0 )); then_10 echo "Found ${#files[@]} log files"_10fi
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:
_10mkdir -p "$dir" # no need to check first_10cp "$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
-ewhen 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")"orBASH_SOURCEto find files next to the script.
Related reading
#Was this resource helpful?