Working with variables

The basics of shell variables

A good deal of personal customization and configuration will involve your setting one or more shell variables. The proper syntax for setting a variable depends on whether or not its value will have embedded whitespace characters, such as spaces or tabs:

$ PWDFILE=/etc/passwd                        setting a variable
$ cat $PWDFILE                               using that variable

$ PWDFILE="/etc/passwd"                      quotes optional here
$ FILES="/etc/passwd /etc/shadow /etc/group" a multiword value

Some important properties of shell variables in Linux:

  1. Variable names are case-sensitive. You can certainly use lower-case variable names, but that's considered heresy and you should avoid it.

  2. There can be no spaces around the equal sign when assigning a value to a variable. This is not negotiable.

  3. Any value that contains whitespace must be enclosed in quotes. For the moment, as long as you're not trying to do anything fancy, either single or double quotes will work. You may put quotes around single-word values if you want, but they're not required.

  4. To view the value of a specific variable, type (for example):

    $ echo $PWDFILE

    To view the value of all current variables, type:

    $ set

  5. Any variables that you set explicitly at the command line are in effect only for the rest of your login session. If you want to make a variable setting permanent, add its definition to your personal .bash_profile file.

But wait. There's more.