10

I'm writing a script in bash and I want it to execute a command and to handle each line separately. for example:

LINES=$(df)
echo $LINES

it will return all the output converting new lines with spaces.

example:

if the output was supposed to be:

1
2
3

then I would get

1 2 3

how can I place the output of a command into a variable allowing new lines to still be new lines so when I print the variable i will get proper output?

Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
ufk
  • 30,912
  • 70
  • 235
  • 386

2 Answers2

15

Generally in bash $v is asking for trouble in most cases. Almost always what you really mean is "$v" in double quotes:

LINES="$(df)"
echo "$LINES"
kubanczyk
  • 5,184
  • 1
  • 41
  • 52
  • 6
    Actually neither assignment to variable needs quotes, because result of expansion is not word-split when assigning to variable. But they don't hurt anything and it's easier to train your muscle-memory to just type double quotes around all expansions. – Jan Hudec Jan 03 '12 at 14:20
7

No, it will not. The $(something) only strips trailing newlines.

The expansion in argument to echo splits on whitespace and than echo concatenates separate arguments with space. To preserve the whitespace, you need to quote again:

echo "$LINES"

Note, that the assignment does not need to be quoted; result of expansion is not word-split in assignment to variable and in argument to case. But it can be quoted and it's easier to just learn to just always put the quotes in.

Jan Hudec
  • 73,652
  • 13
  • 125
  • 172
  • Are you sure? I got the expected results just with `LINES=$(df); echo "${LINES}"`, perhaps IFS is different in our environment. Still +1 as `$(df)` is better than single backtick quotes in @kubanczyk's answer – nhed Jan 03 '12 at 13:59
  • @nhed: Right... assignment to variable never splits. I got confused by error message that turned out to be coming from something else when I tested it here. – Jan Hudec Jan 03 '12 at 14:14
  • @nhed: `$()` is preferred over ``, because it's easier to see and because it is easier to nest. – Jan Hudec Jan 03 '12 at 14:26
  • 1
    @kubanczyk back-ticks is old school, first it is not easy on the eyes (back-ticks within double quotes), second it limits what you can do. Embedding 2 commands, For example: `echo $$ > /tmp/mypid; LINES=$(ps $(cat /tmp/mypid)); echo "${LINES}"` works ... the same with backticks won't – nhed Jan 03 '12 at 14:30