How to preserve line breaks when storing command output to a variable?

LinuxBashShellLine Breaks

Linux Problem Overview


I’m using bash shell on Linux. I have this simple script …

#!/bin/bash

TEMP=`sed -n '/'"Starting deployment of"'/,/'"Failed to start context"'/p' "/usr/java/jboss/standalone/log/server.log" | tac | awk '/'"Starting deployment of"'/ {print;exit} 1' | tac`
echo $TEMP

However, when I run this script

./temp.sh

all the output is printed without the carriage returns/new lines. Not sure if its the way I’m storing the output to $TEMP, or the echo command itself.

How do I store the output of the command to a variable and preserve the line breaks/carriage returns?

Linux Solutions


Solution 1 - Linux

Quote your variables. Here is it why:

$ f="fafafda
> adffd
> adfadf
> adfafd
> afd"

$ echo $f
fafafda adffd adfadf adfafd afd

$ echo "$f"
fafafda
adffd
adfadf
adfafd
afd

Without quotes, the shell replaces $TEMP with the characters it contains (one of which is a newline). Then, before invoking echo shell splits that string into multiple arguments using the Internal Field Separator (IFS), and passes that resulting list of arguments to echo. By default, the IFS is set to whitespace (spaces, tabs, and newlines), so the shell chops your $TEMP string into arguments and it never gets to see the newline, because the shell considers it a separator, just like a space.

Solution 2 - Linux

I have ran into the same problem, a quote will help

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaveView Question on Stackoverflow
Solution 1 - Linuxjaypal singhView Answer on Stackoverflow
Solution 2 - LinuxBobView Answer on Stackoverflow