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

by Oliver; 2014

14. Variables

To declare something as a variable use an equals sign, with no spaces. Let's declare a to be a variable:
$ a=3    # This syntax is right (no whitespace)
$ a = 3  # This syntax is wrong (whitespace)
-bash: a: command not found
Once we've declared something as a variable, we need to use $ to access its value (and to let bash know it's a variable). For example:
$ a=3
$ echo a
a
$ echo $a
3
So, with no $ sign, bash thinks we just want to echo the string a. With a $ sign, however, it knows we want to access what the variable a is storing, which is the value 3. Variables in unix are loosely-typed, meaning you don't have to declare something as a string or an integer.
$ a=3          # a can be an integer
$ echo $a
3
$ a=joe	       # or a can be a string
$ echo $a
joe
$ a="joe joe"  # Use quotes if you want a string with spaces
$ echo $a
joe joe
We can declare and echo two variables at the same time, and generally play fast and loose, as we're used to doing on the command line:
$ a=3; b=4
$ echo $a $b
3 4
$ echo $a$b         # mesh variables together as you like
34
$ echo "$a$b"       # use quotes if you like
34
$ echo -e "$a\t$b"  # the -e flag tells echo to interpret \t as a tab
3	4
As we've seen above, if you want to print a string with spaces, use quotes. You should also be aware of how bash treats double vs single quotes. If you use double quotes, any variable inside them will be expanded (the same as in Perl). If you use single quotes, everything is taken literally and variables are not expanded. Here's an example:
$ var=5
$ joe=hello $var
-bash: 5: command not found
$ joe="hello $var"
$ echo $joe
hello 5
$ joe='hello $var'
$ echo $joe
hello $var
An important note is that often we use variables to store paths in unix. Once we do this, we can use all of our familiar directory commands on the variable:
$ d=dir1/dir2/dir3
$ ls $d
$ cd $d
$ d=..     # this variable stores the directory one above us (relative path)
$ cd $d/.. # cd two directories up

<PREV   NEXT>