Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between "$a" and $a in unix [duplicate]

Tags:

shell

unix

For example:

#!/bin/sh
a=0
while [ "$a" -lt 10 ]
   b="$a"
   while [ "$b" -ge 0 ] do
      echo -n "$b "
     b=`expr $b - 1`
   done
   echo
   a=`expr $a + 1`
done*

The above mentioned script gives the answer in triangle while with out the double quotes, it falls one after the other on diff lines.

like image 802
user2571172 Avatar asked Jul 11 '13 05:07

user2571172


2 Answers

After a variable is expanded to its value, word splitting (i.e. separating the value into tokens at whitespace) and filename wildcard expansion takes place unless the variable is inside double quotes.

Example:

var='foo   bar'
echo No quotes: $var
echo With quotes: "$var"

will output:

No quotes: foo bar
With quotes: foo   bar
like image 194
Barmar Avatar answered Sep 21 '22 12:09

Barmar


Here the difference is how the argument is passed to echo function. Effectively " " will preserve whitespaces.

This:

echo -n "$b "

Is translated to:

echo -n "<number><space>"

While this:

echo -n $b<space>

Will ignore the trailing space and will just output the number:

echo -n <number>

Therefore removing all the spaces that are needed for output to look "triangular".

like image 24
mishik Avatar answered Sep 20 '22 12:09

mishik