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.

Aching back from coding all day?

Inversion Therapy Table

Aching back from coding all day? Try Back Problems

Stretch out your back and relieve your back muscles with inversion therapy. This device counteracts the forces of gravity on the body by decompressing and elongating the spine. By using this product just ten minutes a day, you can be well on your way to improved circulation and posture while relieving muscle aches, back pain and stress.

$$ Check price
119.98119.98Amazon 4.5 logo(1,700+ reviews)

More Back Problems resources

Take your Linux skills to the next level!

How Linux Works

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

In this completely revised second edition of the perennial best seller How Linux Works, author Brian Ward makes the concepts behind Linux internals accessible to anyone curious about the inner workings of the operating system. Inside, you'll find the kind of knowledge that normally comes from years of experience doing things the hard way.

$ Check price
39.9539.95Amazon 5 logo(114+ reviews)

More Linux & UNIX resources

Ad