Ubuntu – Can you help me to understand this explanation of shell quoting

bashcommand lineenvironment-variables

I'm trying to comprehend and reproduce this

I read this section in the book Learning The Bash Shell;
My question about it is below it:

"Notice that we used double quotes around variables (and strings containing them) in these echo examples. In Chapter 1, we said that some special characters inside double quotes are still interpreted, while none are interpreted inside single quotes.

A special character that "survives" double quotes is the dollar sign—meaning that variables are evaluated. It's possible to do without the double quotes in some cases; for example, we could have written the above echo command this way:

$ echo The value of \$ varname is \"$ varname \".

But double quotes are more generally correct. Here's why. Suppose we did this:

$ fred='Four spaces between these words.'

Then if we entered the command # echo $fred, the result would be:

Four spaces between these words.

What happened to the extra spaces? Without the double quotes, the shell splits the string into words after substituting the variable's value, as it normally does when it processes command lines. The double quotes circumvent this part of the process (by making the shell think that the whole quoted string is a single word).

Therefore the command echo "$fred" prints this:

Four spaces between these    words.

The distinction between single and double quotes becomes particularly important when we start dealing with variables that contain user or file input later on."

My question

I have tried to practice with this, but I am confused. Do I put-

$ echo The value of \$ varname is \"$ varname \".
$ fred='Four spaces between these words.'

in a file? Like enter # nano, then put it in there? Or do I just enter it into the terminal? Neither are working. When I entered # nano fred and put it in that file and made it executable and changed "varname" to "fred" and ran ./fred, I got this as a result:

The value of $fred is ""

Can you explain what am I doing wrong?

Best Answer

I've tried to break this down a little bit for you, using your own examples/text as well, check it out:

$ cat fred    
#!/bin/bash

fred='Four spaces between these    words.'

echo "The value of \$fred is $fred"

echo "The next line being printed is simply the results of # echo \$fred"

echo $fred

Running the bash script above prints the following to the terminal/stdout:

The value of $fred is Four spaces between these    words.
The next line being printed is simply the results of # echo $fred
Four spaces between these words.

As well, you can view a terminal video of this here: http://showterm.io/98f56243f60551b338b9f