I am in a confusion with what is meant by the double quotes referring to a variable. For example following two scripts gives the same output. What is really meant by the double quotes?


getent passwd | while IFS=: read a b c d e f ; do
echo login "$a" is "$d"

script 2

#! /bin/sh

getent passwd | while IFS=: read a b c d e f ; do

    echo login $a is $d

Take a look at the Advanced Bash Scripting Guide, specifically section 5.1 which covers quoting variables. The reason you double quote variables is because the contents of the variable may include spaces. A space is typically the boundary character which denotes a break in atoms within a string of text for most commands.

There's a good example there that illustrates this point:

excerpt from the above link

variable2=""    # Empty.

COMMAND $variable2 $variable2 $variable2
                # Executes COMMAND with no arguments. 
COMMAND "$variable2" "$variable2" "$variable2"
                # Executes COMMAND with 3 empty arguments. 
COMMAND "$variable2 $variable2 $variable2"
                # Executes COMMAND with 1 argument (2 spaces).
# Thanks, St├ęphane Chazelas.

In the above you can see that depending on how you quote the variable it's either no arguments, 3, or 1.

NOTE: Thanks to @St├ęphaneChazelas for providing that feedback to the ABS Guide so that it can work it's way back into this site where he's always participating.

| improve this answer | |
  • Is there any scenario where you wouldn't want to enclose a variable with double quotes? – Stevoisiak Dec 31 '19 at 15:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.