place a multi-line output inside a variable
Asked Answered
U

2

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?

Upholsterer answered 3/1, 2012 at 13:41 Comment(0)
A
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"
Alegre answered 3/1, 2012 at 13:43 Comment(1)
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.Nancee
N
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.

Nancee answered 3/1, 2012 at 13:47 Comment(4)
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 answerCarpous
@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.Nancee
@nhed: $() is preferred over ``, because it's easier to see and because it is easier to nest.Nancee
@Alegre 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'tCarpous

© 2022 - 2024 — McMap. All rights reserved.