So far, we have used a simple double-quoting mechanism to encase the strings that we want to use with echo.
In the first script, it does not matter if we use single or double quotes. echo "Hello World" will be exactly the same as echo 'Hello World'.
However, this is not the case in the second script, so it is very important to understand the quoting mechanisms available in bash.
As we have seen, using double quotes in echo "Hello $1" will result in Hello fred or whatever the supplied value is. Whereas, if we use single quotes in echo 'Hello $1', the printed output on the screen will be Hello $1; that is, we see the variable name and not its value.
The idea of the quotes is to protect special characters, such as a space between the two words; both quotes protect the space from being misinterpreted. The space is normally read as a default field, separated by the shell. In other words, all characters are read by the shell as literals with no special meaning. This has the knock-on effect of the $ symbol printing its literal format rather than allowing bash to expand its value. The bash shell is prevented from expanding the variable's value as it is protected by the single quotes.
This is where the double quote comes to our rescue. The double quote will protect all the characters except the $, allowing bash to expand the stored value.
If we ever need to use a literal $ within the quoted string, along with variables that need to be expanded, we can use double quotes, but escape the desired $ with the backslash (\). For example, echo "$USER earns \$4" would print as Fred earns $4 if the current user were Fred.
Try the following examples at the command line using all quoting mechanisms. Feel free to up your hourly rate as required:
$ echo "$USER earns $4" $ echo '$USER earns $4' $ echo "$USER earns \$4"
The output is shown in the following screenshot: