An Introduction to the Command-Line (on Unix-like systems)

by Oliver; 2014

15. Escape Sequences

Escape sequences are important in every language. When bash reads $a it interprets it as whatever's stored in the variable a. What if we actually want to echo the string $a? To do this, we use \ as an escape character:
$ a=3
$ echo $a
3
$ echo \$a
$a
$ echo "\$a"  # use quotes if you like
$a
What if we want to echo the slash, too? Then we have to escape the escape character (using the escape character!):
$ echo \\\$a  # escape the slash and the dollar sign
\$a
This really comes down to parsing. The slash helps bash figure out if your text is a plain old string or a variable. It goes without saying that you should avoid special characters in your variable names. In unix we might occasionally fall into a parsing tar-pit trap. To avoid this, and make extra sure bash parses our variable right, we can use the syntax ${a} as in:
$ echo ${a}
3
When could this possibly be an issue? Later, when we discuss scripting, we'll learn that $n, where n is a number, is the nth argument to our script. If you were crazy enough to write a script with 11 arguments, you'd discover that bash interprets a=$11 as a=$1 (the first argument) concatenated with the string 1 while a=${11} properly represents the eleventh argument. This is getting in the weeds, but FYI.

Here's a more practical example:
$ a=3
$ echo $a		# variable a equals 3
3
$ echo $apple		# variable apple is not set

$ echo ${a}pple		# this describes the variable a plus the string "pple"
3pple

<PREV   NEXT>