6

I was hacking at a small script earlier and noticed something I can't explain.

Running this command

(time wget --spider http://www.google.co.uk/) 2>&1  | egrep 'real|response'

gives me this output (which I expect)

HTTP request sent, awaiting response... 200 OK
real    0m0.086s

I capture the output above in a variable

Result=$((time wget --spider http://www.google.co.uk/) 2>&1  | egrep 'real|response')

If I

echo "$Result"   

I get the expected output

HTTP request sent, awaiting response... 200 OK
real    0m0.086s

However if I

echo $Result

I get

HTTP request sent, awaiting response... 200 OK real    0m0.086s

Why is that ?

2 Answers2

11

The echo $Result command will convert the value of the variable into multiple arguments for echo, splitting on any whitespace, and echo prints all the arguments separated by spaces. On the other hand, echo "$Result" will put the whole string, including whitespace, into the first and only echo argument, which gets printed directly.

Adam Byrtek
  • 1,339
0

Adam's answer pointed me in the right direction in that it is related to whitespace. More specifically the \n between the two lines is interpreted as whitespace and is converted to a single , when using $Result but is left as \n when using "$Result".

I'd never really considered '\n' to be whitespace before.

  • 1
    The variable $IFS (Internal Field Seperator) governs what is classed as whitespace.. eg. echo -n "$IFS" | xxd -p ... returns 20090a ... space, tab, newline (xxd is a hex dump utility packaged with vim) – Peter.O May 27 '11 at 13:22