Using Variables in Bash

The Absolute Basics

Like any language, variables1If you are very new to programming please read up on variables in programming before continuing. in Bash have their own unique quirks. Here is quick a guide for those new to working with Bash variables. Let’s jump right in.

Creating and Assigning Variables

The basic syntax to create and assign a value to variable is shown below.

# Create a variable called MyVar and assign the value "HELLO" to it.

MyVar=HELLO

Displaying Variables

Probably the most common way to display a variable in Bash is to use the echo command, likely followed in popularity by the printf command. For the purposes of simply displaying variables either of these commands will suffice. An example of using both is shown below. Note that I have added “\n” to add a newline to the output of printf — something that echo does automatically.

mindyourbits$ MyVar=Hello
mindyourbits$ echo "$MyVar"
Hello
mindyourbits$ printf "$MyVar\n"
Hello

Comparing Variables

The two primary methods for comparing items involves placing the items you want to compare within either single brackets “[ ]” (equivalent to the test command) or double brackets “[[ ]]” and then using comparison operators to decide the type of comparison you want.

The decision to use double versus single brackets often causes confusion. For this reason, I recommend getting in the habit of using double square brackets excusively — unless you have a valid reason to use single square brackets. My reasoning behind this suggestion is that double brackets are more robust and it avoids having to decide each time, saving valuable mental energy.

For more advanced items, like floating point numbers you can use bash’s shell arithmetic features. This is done through the use of double parentheses “(( ))”, but I won’t go into that in this post, mostly out of laziness.

Here are a few examples:

Comparing Strings

## Simple String Comparison ##

MyVar="MindYourBits"
if [[ "MindYourBits" == "$MyVar" ]]; then
    echo "The strings match!"
else
    echo "The strings do not match!"
fi

Comparing Integers

## Simple Integer Comparison ##

num1="5"
num2="5"

if [[ num1 -eq num2 ]]; then
   echo "The numbers are equal!"
else
   echo "The numbers are not equal!"
if

## Floating Point Number Comparison ##

A Few Things to Keep in Mind

Spaces

If you use spaces on either side of the variable, you will recieve a “command not found” error referencing either the variable name or the value you are trying to assign. This is because bash uses spaces to delineate commands and thinks that we’re trying to run a command instead of trying to assign a variable. Below are some examples of what not to do when creating and assigning values to variables.

mindyourbits$ MyVar = Hello
-bash: MyVar: command not found

mindyourbits$ MyVar= Hello
-bash: Hello: command not found

mindyourbits$ MyVar =Hello
-bash: MyVar: command not found

Dollar Signs

Using a dollar sign ($) is necessary to recall a variable after it is created. Without using the dollar sign in front of the variable, bash will regard the string as literal. I only mention this because many languages such as Python or Java do not require an indicator like the dollar sign to recall a previously created variable.

Quotes

When assigning a variable in bash, if the variable has spaces, using quotes around it is a requirement. Usually, using double quotes will work just fine. But there are instances where using single quotes makes more sense.

In relation to displaying or recalling variables that are already set, there are situations in which Bash may not interpret a variable as we expect. For instance, if a variable has spaces in it. For this reason I recommend always using quotes around variables in Bash. I know this sounds a bit hard edged, but Bash can be pretty unforgiving in many ways.

So, in short:

  • When assigning variables — quotes are optional unless there is whitespace, such as a space or a tab.
  • When using variables — using quotes is a good habit to have could be called a best practice.

Pitfalls to Avoid

Bash is considered a weakly typed language, which — for our purposes — means that variables in Bash do not require programmers to specify whether a variable is meant to be a string, a number, or something else. This is often referred to as “typing” or “setting the type” of the variable.

To compare this with a strongly typed language here is an example of a variable declaration and assignment in C# (referred to as “C Sharp”):

// The type of the variable "name" is specified as "string"
string name = "HELLO";

Bash’s lack of typing features is one area that separates it from more robust languages. This usually is not a problem. But as with any language, once we start to understand how things can go wrong we can usually avoid most issues little effort.

Author: Dave Adams
I've been working on various software projects for over 12 years now. I love creating new things and playing with ideas to find paths forward. I would consider myself both creative and technical. I made this site primarily to assist my own learning and as a creative outlet. I also enjoy playing guitar, reading, writing, and working out.

Leave a Reply

Your email address will not be published. Required fields are marked *