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

Conventions

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
34

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?

Self-Massage Tool

Aching back from coding all day? Try Back Problems

Relieve spasms, tight muscles, trigger points and pressure points with the Body Back Buddy! This trigger point massage is designed to help you self-message any area of your body - especially those that are hard to reach. Keeping your muscles relaxes and out of contraction is importan in helping to reduce pain and prevent muscle injury.

$ Check price
29.9529.95Amazon 4.5 logo(3,443+ reviews)

More Back Problems resources

Ad