Interview Prep/Shell Scripting/Variables, quoting and expansions

Why should you almost always quote variable expansions? Show what goes wrong.

BeginnerConceptVariables, quoting and expansions
Answer

Unquoted expansions undergo word splitting on IFS and pathname expansion.

file="monthly report.csv"
rm $file        # rm: cannot remove 'monthly': No such file or directory
rm "$file"      # correct

pattern="*"
echo $pattern   # lists every file in the directory
dir=""
rm -rf $dir/*   # becomes rm -rf /*

Quote "$var", "$(cmd)" and "${arr[@]}". The exceptions are deliberate: inside [[ ]], on the right side of an assignment, and when you intentionally want splitting (documented with a comment).

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Variables, quoting and expansions