A few quick tips on using variables in your Bash scripts. Nothing fancy here, just good practices that we often overlook.

Simple stuff

Assigning variables from user input

Reading variables that contain a backslash

Assigning multiple variables from command output

Assigning multiple variables from another variable

Assigning multiple variables from pipe


Checking Variables

If the variable not set, say something

Check if the variable is set and is not a space

If one or more variables not set, say something
If one or more variables not set, say something and do something
If variable not set, set it to some default value
If a variable is not an integer, set it to zero
If multiple variables are not set, assign them a default value

Working with arrays of variables

If you really have lots and lots of variables that require different default values, you may use a table. Parse this table to populate two arrays: one containing names of the variables and the other – their default values. Let’s say your table.txt looks like this:

We will use it to build two arrays:

Now we can read the array_variables array, check if the variables are set and, if not, assign a corresponding default value from the array_defaults array:

And to check that the variables have been set: