The best way to think of variables is as placeholders for values. They can be permanent (static) or transient (dynamic), and they will have a concept called scope (more on this later). To get ready to use variables, we need to think about the script you just wrote: my_first_script.sh. In the script, we could have easily used variables to contain values that are static (there every time) or dynamic ones created by running commands every time the script is run. For example, if we would like to use a value such as the value of PI (3.14), then we could use a variable like this short script snippet:
PI=3.14
echo "The value of PI is $PI"
If included in a full script, the script snippet would output:
The value of Pi is 3.14
Notice that the idea of setting a value (3.14) to a variable is called assignment. We assigned the value of 3.14 to a variable with the name PI. We also referred to the PI variable using $PI. This can be achieved in a number of ways:
echo "1. The value of PI is $PI"
echo "2. The value of PI is ${PI}"
echo "3. The value of PI is" $PI
This will output the following:
1. The value of PI is 3.14
2. The value of PI is 3.14
3. The value of PI is 3.14
While the output is identical, the mechanisms are slightly different. In version 1, we refer to the PI variable within double quotes, which indicates a string (an array of characters). We could also use single quotes, but this would make this a literal string. In version 2, we refer to the variable inside of { } or squiggly brackets; this is useful for protecting the variable in cases where this would break the script. The following is an example:
echo "1. The value of PI is $PIabc" # Since PIabc is not declared, it will be empty string
echo "2. The value of PI is ${PI}" # Still works because we correctly referred to PI
If any variable is not declared and then we try to use it, that variable will be initialized to an empty string.
The following command will convert a numeric value to a string representation. In our example, $PI is still a variable containing a number, but we could have created the PI variable like this as well:
PI="3.14" # Notice the double quotes ""
This would contain within the variable a string and not a numeric value such as an integer or float.
Wait! You say there is a difference between a number and a string? Absolutely, because without conversion (or being set correctly in the first place), this may limit the things you can do with it. For example, 3.14 is not the same as 3.14 (the number). 3.14 is made up of four characters: 3 + . + 1 +4. If we wanted to perform multiplication on our PI value in string form, either the calculation/script would break or we would get a nonsensical answer.
Let's say we want to assign one variable to another. We would do this like so:
VAR_A=10
VAR_B=$VAR_A
VAR_C=${VAR_B}
If the preceding snippet were within a functioning Bash script, we would get the value 10 for each variable.