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!

Command Line Kung Fu

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

Command Line Kung Fu is packed with dozens of tips and practical real-world examples. You won't find theoretical examples in this book. The examples demonstrate how to solve actual problems. The tactics are easy to find, too. Each chapter covers a specific topic and groups related tips and examples together.

$ Check price
14.9914.99Amazon 4.5 logo(27+ reviews)

More Linux & UNIX resources

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

Ad