6

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.

codeforester
  • 39,467
  • 16
  • 112
  • 140
user2571172
  • 69
  • 1
  • 2
  • 1
    Note: "echo -n" doesn't work the same way on all shells, on some systems this will just output "-n" instead of suppressing the newline. –  Jul 11 '13 at 05:30

3 Answers3

10

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
Barmar
  • 741,623
  • 53
  • 500
  • 612
4

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".

mishik
  • 9,973
  • 9
  • 45
  • 67
0

There are errors in your script:

  • no do after 1st while
  • no ; before do after 2nd while
  • why asterisk on done* at the end?

Now to answer your question. If used as a paramenter:

  • "$a" is one argument.
  • $a (without quotes) is possibly multiple arguments:

Compare:

v='a b';  set $v; echo "\$#=$#, \$1=\"$1\",  \$2=\"$2\""  
$#=2, $1="a",  $2="b"

v='a b'; set "$v"; echo "\$#=$#, \$1=\"$1\",  \$2=\"$2\""  
$#=1, $1="a b",  $2=""
Leonid Volnitsky
  • 8,854
  • 5
  • 38
  • 53