Advanced

Variables and quoting

Shell variables are text substitution done by the shell before the command runs, which is why they behave nothing like variables in a program. The important consequence is that an unquoted variable is split into words, and a name with a space becomes two arguments.

What you will see

The script stops with 'not set' rather than continuing with an empty argument.

About 1 min of reading

Try It

Watch word splitting bite.

1

Set a name with a space

name='My File' wc -w $name

Before you run it, say out loud what it will print. Then open the answer.

What it prints
An error about two files named My and File - the value was split into two arguments.
2

Quote it

wc -w "$name"

Before you run it, say out loud what it will print. Then open the answer.

What it prints
The count for the single file, or a clean error about that one name.
3

Guard an unset variable

echo "${missing:?not set}"

Before you run it, say out loud what it will print. Then open the answer.

What it prints
The script stops with 'not set' rather than continuing with an empty argument.

Data Flow

A name is replaced by text, then split.
1 Set the variable
↓
2 Expand it where used
↓
3 Word splitting happens unless quoted
↓
4 The command receives the resulting words
Why this works
Empty variables are dangerous

An unset variable expands to nothing, so a command loses an argument and does something different rather than something wrong. ${var:?message} stops the script with your message, which is the guard worth using by default.

Quoting inside the quotes

Double quotes allow expansion, single quotes do not. That difference is the whole reason both exist, and mixing them by accident is what turns a message into a command substitution.

Examples

Assign without spaces

name=value with no spaces around the equals. With spaces, the shell reads name as a command and value as its argument, which is a different failure than the one you expected.

Quote the expansion

"$file" keeps the value as one argument. $file splits on spaces and drops empty values. The quoted form is almost always the one you want, and the cost is two characters.

Positional parameters

$1 $2 are the arguments the script was called with, and $0 is its own name. Checking that they are present at the top of a script is the guard that turns a silent wrong run into a clear error.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Running a script
Previous Lesson
Running a script
Next Lesson
Finding files by rule
Finding files by rule →