What is the difference between echo $var and echo "$var"

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?

0

2 Answers

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.

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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like