bashbash4

place a multi-line output inside a variable


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?


Solution

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