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
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.
This is the script as it runs
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