Dualo
Bash / Shell Scripting

Variables & quoting

Store values, interpolate them, and — most importantly — quote them to survive spaces, globs, and special characters.

1 min read

Variables in Bash are plain text. Assign with name=value (no spaces around =!). Read with $name or ${name}. Example: greeting='hello'; echo "$greeting world".

Three quoting styles: single quotes '...' = literal text, no expansion ($var stays as-is). Double quotes "..." = expand variables and command substitution but preserve spaces. No quotes = the shell splits on whitespace and expands globs — often wrong.

The #1 bash bug: forgetting to quote. rm $file when $file='my document.txt' will try to remove two files: my and document.txt. Always quote variables that might contain spaces or special chars: rm "$file".

Command substitution: $(cmd) runs cmd and substitutes its output. today=$(date +%F) stores today's date. Prefer $(...) over the older backtick form `...` — nests cleanly, easier to read.

Special variables: $? (exit code of last command), $$ (current PID), $HOME, $USER, $PATH. Parameters in scripts: $0 (script name), $1..$9 (positional args), $@ (all args), $# (count).

Grounded on https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion

Next up

Control flow — if, for, while, case

Branch on exit codes, loop over lists or streams, match patterns. Bash control flow is quirky — exit code 0 means true.