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.

Aching back from coding all day?

Prism Glasses

Aching back from coding all day? Try Back Problems

Ever feel achy from sitting crunched up on your computer table? Try lying down with these optical glasses that allow you to work on your laptop while lying flat on your back. This is the perfect solution with those with limited mobility or those who wish to prevent neck cramps and back strains.

$ Check price
4.454.45Amazon 4 logo(128+ reviews)

More Back Problems resources

Take your Linux skills to the next level!

Linux for Beginners

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

Linux for Beginners doesn't make any assumptions about your background or knowledge of Linux. You need no prior knowledge to benefit from this book. You will be guided step by step using a logical and systematic approach. As new concepts, commands, or jargon are encountered they are explained in plain language, making it easy for anyone to understand.

$ Check price
24.9924.99Amazon 4.5 logo(101+ reviews)

More Linux & UNIX resources