Bash Shell Scripting Part 4 – Variables

Bash Shell ScriptingNow that we have successfully created and executed a shell script, it’s time to start building on the functionality available to shell scripts.

The topics to come may sound heavy, but they’re actually very cool, and can serve as a basic primer for anyone interested in learning programming.

For anyone not interested in programming, the logic that can be applied in shell scripting is none-the-less a useful skill to have.

The first of these, that I found downright enthralling (when I first began programming years ago), are variables.

What Are Variables?

The reason that shell scripts are so flexible can be boiled down to the use of variables within them.

The word variable is defined as an element or feature that is “not consistent”, “subject to change”, and “adaptable”.

Used in a programming (scripting) context, a variable is a storage location that can be assigned a value or values on the fly, or dynamically.

Variables are invaluable tools in a scripting environment. They can store numbers, text, file names, command results, or just about any data you can think of.

Variables can be written, overwritten, added to, modified, searched through, etc.

Perhaps the most fundamental function of a variable is the ability to use one for each data element in a script, so that you can “call” the relevant variable each time it is needed throughout a script, rather than re-type the data itself. This way, any future changes to the data in question is made much easier by having only one location where the data needs to be changed, rather than multiple random locations throughout a script.

Types of Variables

Many programming languages define types of variables based on their values (or the values they allow to be stored in each type). In some of those cases, the type of variable must be stated each time a variable is created, or defined.

Bash shell scripting allows for a much more relaxed atmosphere surrounding the creation of variables, as their types do not have to be defined. There are, in fact, only two types that you need to be aware of.

Local Variables: Local variables are those (usually created by the script’s author) that will only work within the confines of the current shell.

Global Variables: Global variables (often environmental or system variables that are defined already by the system) are available in all shells.

To see the current system (global) variables, use the set, env or printenv commands.

How to Create (Define) a Variable

In shell scripting, variables are defined (created) by simply stating the variable name and variable value with an equal sign in between them.

There should not be spaces between the variable name and the variable value.

Use quotation marks to enclose strings (multiple words/etc.) in the variable value.

Single quotes indicate that the variable values should be treated literally, and not interpreted, etc.

Double quotes allow characters with special meanings (like other variables) to be used/interpreted/etc.

Inside the quotation marks, use a backslash \ to “escape” characters that you want treated literally, rather than interpreted. This is especially useful to escape quotes and dollar signs.

VariableName=VariableValue or GwenVar1='The Variable Contents'

A NULL (empty) variable can be defined (and assigned a value later on) by leaving out the value.

VariableName=

The output of a command can be assigned to a variable by making the command the value of the variable. To do this, enclose the command in parenthesis and precede it with a dollar sign.

ResultsOfListDir=$(ls)

Existing variables can be made read-only by stating readonly VariableName (but have fun trying to unset it later!)

Variable Naming Conventions

All variable names must adhere to a specific set of rules to be valid. The rules often differ for each programming/scripting language that uses variables.

For Bash shell scripts, the variable-naming rules are simply:

  1. Alphanumeric characters and underscores can be used in variable names.
  2. Spaces, punctuation, and other non-alphanumeric characters can not be used in variable names.
  3. User-defined variable names must begin with a letter or an underscore.
  4. Variable names are case-sensitive.
    • It is recommended to use lowercase for user-defined (local) variables.
    • Environmental or global variables are usually defined (or already defined) in uppercase.

Using meaningful names for variables is just as — or more — important as when naming files, etc. You will want to be able to easily understand your script variables at a later date.

How to Use a Variable

After a variable is created/defined, it can be used (called, referenced) at any time(s) throughout the remainder of the script.

To use a variable, call it by placing a dollar sign $ before the variable name.

echo $VariableName

Curly braces can be used in cases where variables immediately surround data, to differentiate the variable name from the data. The curly braces are used after the dollar sign.

echo "The variable says: ${VariableName}"

Array Variables

Arrays are a set of variables grouped together with a common name and different values.

An index number, in braces [], is appended to the variable name to differentiate each one.

The index number begins at 0 by default.

GwenArray[0]="First Value"
GwenArray[1]="Second Value"
GwenArray[2]="Third Value"
echo ${GwenArray[1]}

How to Unset a Variable

There is no requirement to “unset” variables when you are done with them, but the ability exists, if the need ever arises.

You may end up un-setting variables in scripts from time to time, if for no other reason than to free up resources.

To unset a variable, simply use unset as a command, followed by the variable name.

unset VariableName

(Read-only variable names cannot be unset.)

Summary

All of these details about how to create and use variables may go in one eye and out the other, but keep in mind what you can and then refer back later. As we progress, the whole picture will make each part more clear.

Leave a Reply

You have to agree to the comment policy.

Scroll to top