Common Quoting Pitfalls and Safe Syntax

Updated

October 31, 2026

Common Quoting Pitfalls and Safe Syntax

Failing to quote variables correctly is the source of CVE vulnerabilities and catastrophic production outages.

Pitfall 1: Unquoted Variables in Commands

# Catastrophic error if target_dir is empty or contains spaces
target_dir="/tmp/demo build"
rm -rf $target_dir
# rm -rf /tmp/demo build -> Deletes both /tmp/demo AND current directory 'build'!

# Safe:
rm -rf "$target_dir"

Pitfall 2: Unquoted Test Conditions in [ ]

# If $user is empty, this evaluates to: [ = "admin" ] -> syntax error!
[ $user = "admin" ]

# Safe POSIX:
[ "$user" = "admin" ]

# Safe Bash:
[[ $user == "admin" ]]

Pitfall 3: Storing Commands in Variables

# WRONG: Trying to store complex commands with flags or quotes in a variable
cmd="grep -E 'ERROR|FATAL' /var/log/syslog"
$cmd # Fails because quotes inside variables are not parsed after expansion!

# CORRECT: Use a bash function or array
run_search() {
    grep -E 'ERROR|FATAL' /var/log/syslog
}

# Or array:
cmd=(grep -E "ERROR|FATAL" "/var/log/syslog")
"${cmd[@]}"