Understanding Variables

The single most thing that gives a Bash script flexibility is using variables. A variable is just a container that you can fill with numbers, text, entire files, anything you can think of. You can assign a variable and use it throughout the script or change it based on how the script runs. it is very important to understand variables in order to make any sort of script useful especially when using loops.

Example 1: Store predefined information in a variable

MYFAVCOLOR="Blue"
echo "My favorite color is: $MYFAVCOLOR"
./myscript
My favorite color is: Blue

Line 1 tells the computer that when we call the variable MYFAVCOLOR it is the letters “Blue”. In line 2 we use “echo” to print text on the screen and we print the text that will never change ‘My favorite color is:’ and then we call our variable. Bash knows its our variable because of the $, that is how you call a variable without the $ it would literaly print the text ‘MYFAVCOLOR’ so it then puts the contents of the variable which is the letters ‘Blue’.

Now a script that only displays that every single time you run it would be pretty boreing and not very useful so that is where you can get user input. So in this example we will want to find out what the users favorite color is and then display it back to them, and also let them know what my favorite color is.

MYFAVCOLOR="Blue"

echo "What is your favorite color?"
read USERFAVCOLOR

echo "Your favorite color is $USERFAVCOLOR, my favorite color is $MYFAVCOLOR"

This is the script as it runs

./myscript
What is your favorite color?
Green
Your favorite color is Green, my favorite color is Blue

The last example I will be showing in this post will be to overwrite a variable during a script. In this script we ask the user to put in their favorite color and we will read it back to them, change it and read it back again

echo "What is your favorite color?"
read USERFAVCOLOR

echo "Your favorite color was $USERFAVCOLOR"
USERFAVCOLOR="Orange"

echo "Your favorite color is now $USERFAVCOLOR"
./myscript
What is your favorite color?
Green
Your favorite color was Green
Your favorite color is now Orange

Be the first to comment

Leave a Reply

Your email address will not be published.


*