Chapter 5. Basic Scripting: Shell Variables

bash shell programming is a lot like any kind of programming, and that includes having variables—containers that hold strings and numbers, which can be changed, compared, and passed around. bash variables have some very special operators that can be used when you refer to a variable. bash also has some important built-in variables, ones that provide important information about the other variables in your script. This chapter takes a look at bash variables and some special mechanisms for referencing variables, and shows how they can be put to use in your scripts.

Variables in a bash script are often written as all-uppercase names, though that is not required—just a common practice. You don’t need to declare them; just use them where you want them. They are basically all of type string, though some bash operations can treat their contents as a number. They look like this in use:

# trivial script using shell variables
# (but at least it is commented!)
echo $MYVAR
# similar but with no quotes
echo $MY_2ND
# quotes are needed here:
MYOTHER="more stuff to echo"

There are two significant aspects of bash variable syntax that may not be intuitively obvious. First, in the assignment, the name=value syntax is straightforward enough, but there cannot be any spaces around the equals sign.

Let’s consider for a moment why this is the case. Remember that the main purpose of the shell is to launch programs—you ...

Get bash Cookbook, 2nd Edition now with the O’Reilly learning platform.

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