Cover by Cameron Newham, JP Vossen, Carl Albing

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

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 the 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!)
	MYVAR="something"
	echo $MYVAR
	# similar but with no quotes
	MY_2ND=anotherone
	echo $MY_2ND
	# quotes are needed here:
	MYOTHER="more stuff to echo"
	echo $MYOTHER

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

Let's consider for a moment why this is the case. Remember that the basic semantics of the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required