Using Variables

A variable is a chunk of memory to which you can store arbitrary data, and retrieve it again, just by referencing its name. There is no need to explicitly allocate the memory required, and no need to free the memory after the need for it has gone. Although some languages have complex garbage-collection features, shell scripts generally tend to be working with relatively small amounts of data and for a reasonably short period of time, so a much simpler model suffices.

The shell is somewhat unique in the syntax for using variables. Many (such as Perl, PHP, and others) use a dollar sign prefix whenever the variable is referred to; others (such as Java or C) use no specific markup to identify a variable; the context is enough to make it clear that the code is referring to a variable.

note.ai

Sometimes you need a dollar sign to reference a variable (echo $variable) and sometimes you need to not have a dollar sign (variable=foo). Sometimes you need curly braces around the name (echo ${variable}bar) and sometimes it doesn’t matter (echo $variable bar). There is logic behind these apparently arbitrary rules, so don’t panic; it is all perfectly comprehensible.

In the shell, when you refer to the value stored by a variable, you put a dollar symbol in front of the name of the variable:

echo $PATH

When you write to a variable, you simply use its name (the dollar sign here is ...

Get Shell Scripting: Expert Recipes for Linux, Bash, and More now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.