1

On the terminal (bash) when I type

var=someValue

echo $var    --> 1
echo "$var"  --> 2

Form 1 and 2 I get the same results, so what is the difference between them?

When should we use double quotes, and when should we not use them?

5

There is no difference between echo $var and echo "$var".

However for other commands such as ls (list files) there could be a big difference.

Try this in your terminal:

$ touch "File A"

$ var="File A"

$ ls $var
ls: cannot access 'File': No such file or directory
ls: cannot access 'A': No such file or directory

$ ls "$var"
File A

The double quotes " tells Linux to treat everything in between as a single entity. Without the double quotes everything inside is treated as separate entities delineated by spaces.

So in the first example $var is two different things "File" and "A".

In the second example "$var" is one thing "File A".

The echo command automatically processes a single word or multiple words until the end of the line as one thing. Many other commands expect one or many things.

0

The difference comes when you store a multi line string in a variable and try to echo it.

Try this:

$var="this is a
line of
code"

$ echo $var
this is a line of code

$ echo "$var"
this is a
line of
code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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