01. Variables

Variables are used to store values. They may be empty, in which case they are given a value of null.

Two types of variables

Global variables

Global variables are available in all shells. To view global variables, use the printenv command.

Local variables

Local variables include all global variables, plus those that are available only on the current shell. To view just local variables, we can pipeline the printenv and set output.

$ cat printenv.sorted set.sorted | sort | uniq -u


Here are some important conventions to hold when using variables. Be sure to read through this list!

Naming conventions

  • Variables must start with a letter (a-zA-Z) or underscore (_).
  • Variables may then contain any number of letters (a-zA-Z), digits (0-9) or underscores (_).
  • There is no limit in characters, but a sensible programmer will make it long enough to be descriptive, and short enough to type out.

Utilization conventions

  • Use quotes if your variable value contains a space.
  • When you want the shell to expand your variable, include a $ in front.
  • Wrap a variable around in quotes unles you have a good reason not to. echo "$VAR"
  • Wrap variable names around braces ({}) to avoid confusion. ${VAR}a is certainly different from $VARa.

Assigning values

When assigning variables, make sure that there aren't any intervening spaces between the variable, the assignment variable (=) and value. For example, the following is incorrect syntax:

$ TEST = 'Hello world!'
-bash: =: command not found

This is because the = operator is interpreted as a command, while anything trailing is considered its arguments.

$ test='Hello world!'
$ echo $test
Hello world!
$ my_age=34
$ echo $my_age

Remember that when assigning values to variables, a $ sign in unnecessary, but once you want the shell to expand a variable's value, it is.

Take your Linux skills to the next level!

System Admin Handbook

Take your Linux skills to the next level! Try Linux & UNIX

This book approaches system administration in a practical way and is an invaluable reference for both new administrators and experienced professionals. It details best practices for every facet of system administration, including storage management, network design and administration, email, web hosting, scripting, and much more.

$ Check price
74.9974.99Amazon 4.5 logo(142+ reviews)

More Linux & UNIX resources

Aching back from coding all day?

Foam Seat Cushion

Aching back from coding all day? Try Back Problems

This foam seat cushion relieves lowerback pain, numbness and pressure sores by promoting healthy weight distribution, posture and spine alignment. Furthermore, it reduces pressure on the tailbone and hip bones while sitting. Perfect for sitting on the computer desk for long periods of time.

$ Check price
99.9599.95Amazon 4.5 logo(9,445+ reviews)

More Back Problems resources