Ready to Start Your Career?

Understanding Variable Labels/Values in BASH: The "Newbie" Guide

dedeij 's profile image

By: dedeij

December 15, 2016

variable-values-in-bash(Note: This article assumes you know what a terminal is, and are familiar with some basic CLI commands.)Hello Everyone,In this topic, I am going to distinguish between Variable labels and Variable Values. This is a very basic fundamental concept. However, thinking back to my first BASH scripting class, many of my fellow students had trouble understanding the difference. So I'm going to my best to explain the difference using examples in laymen's terms.I am choosing to use BASH for this example, as it doesn't require anything more than assigning a value to a label. Now, just what am I talking about.When you open a terminal you can assign variables like this:  $> MeatDrawer="STEAK"What the above does is assigns the VALUE "Juicy Steak" to a variable with the LABEL "MeatDrawer"Now you can ECHO that variable.$>ECHO "You pulled a nice juicy MeatDrawer out of the fridge"result$>You pulled a nice juicy MeatDrawer out of the fridgeWhat the heck! That's not what I wanted!It's supposed to say "You pulled a nice juicy STEAK out of the fridge!"Dumb Computer...I said MeatDrawer="STEAK"...What's wrong I'm quitting this stupid class. It doesn't make any sense, and it doesn't do what I wanted, I don't get it.Well, don't quit just yet. There is a trick...and it's an important one. To get VALUE out of a VARIABLE you need to include a '$' before the variable name.$>ECHO $MeatDrawerresult$>STEAKThe dollar sign before the variable label tells the computer to reach inside the variable with that label and get VALUE out of it.Now how you would fix our original ECHO line below?$>ECHO "You pulled a nice juicy MeatDrawer out of the fridge" If you said$>ECHO "You pulled a nice juicy $MeatDrawer out of the fridge" You'd be correct!You can think of variables like drawers or even jars with labels on the outside. You can label them whatever you want, but the value is what you decide to put in them. And again, if you want to tell the computer to get the value out of a variable, in BASH you simply put a '$' before the label and it will give you the value.Here are a few more examples.$>Jar1="Salt"$>ECHO "The first jar now contains $Jar1"(We used the $ to tell the computer to look inside jar1)$>The first jar now contains Salt$>Jar2="Pepper"$>ECHO "The second jar now contains Jar2"$>The second jar now contains Jar2(oops, we forgot the dollar sign, computer doesn't know to look inside and get the value of what's inside, let's fix that)$>ECHO "The second jar now contains $Jar2" (We remembered the dollar sign this time!)$>The second jar now contains Pepper  (Yay! it worked).To reiterate, Variable labels are just that, LABELS! The value of a variable is what you put inside that variable.Hopefully, this has made it a little clearer for some of you and been a refresher for others. Thanks for reading.
Schedule Demo