Variables and quoting

Updated November 1, 2026

A variable in bash is a name that stands for some text. Assignment has no spaces around the =.

name=alice
n=$(wc -l < ~/data/words.txt)
echo "$name: $n"

Sample output

$ n=$(wc -l < data/words.txt)
$ echo "$n"
3
$ n=$(wc -l data/words.txt)
$ echo "$n"
3 data/words.txt

$(...) is command substitution: bash runs the command inside and inserts its output as text.

Double quotes "$n" keep the value as one piece. Without quotes bash splits the value on spaces and expands patterns like *, which is a common source of bugs.

Common mistakes

Spaces around = turn an assignment into a command. name = alice gives bash: name: command not found: bash saw a command called name with the arguments = and alice. A space on one side fails differently: name= alice prints bash: alice: command not found, because there bash runs alice with an empty name in its environment.

A typo in a variable name is not an error. echo "[$name] [$naem]" prints [alice] []: an unknown name expands to an empty string and the script carries on with emptiness in place of a value. That is what set -u is for; it stops on that line.

A tilde inside quotes is not expanded. cd "~/data" gives bash: cd: ~/data: No such file or directory even though the directory exists: bash substitutes the home path only for a bare tilde, before quoting. When the path has to be quoted, write "$HOME/data".

Used in

You need this in the lesson Bash: writing scripts.