title: Shell scripting, store command output in variable and preserve formatting
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/613572/capturing-multiple-line-output-to-a-bash-variable">Capturing multiple line output to a bash variable</a>  </p>
  </blockquote>
  
  
  
  <p>I have what is probably a basic scripting question, but I haven't been able to find an answer anywhere that I've looked.</p>
  
  <p>I have an awk script that processes a file, and spits out a list of disabled systems. When I call it manually from the command line, I get formatted output back:</p>
  
  <pre><code>$awk -f awkscript datafile
  
  The following notifications are currently disabled:
  
  host: bar
  host: foo
  </code></pre>
  
  <p>I am writing a wrapper script to call from my crontab, which will run the awk script, determine if there is any output, and email me if there is. It looks like (simplified):</p>
  
  <pre><code>BODY=`awk -f awkscript datafile`
  if [ -n "$BODY" ]
  then
  echo $BODY | mailx -s "Disabled notifications" me@mail.address
  else
  echo "Nothing is disabled"
  fi
  </code></pre>
  
  <p>When run this way, and confirmed by adding an <code>echo $BODY</code> into the script, the output is stripped of the formatting (newlines are mainly what I'm concerned with), so I get output that looks like:</p>
  
  <pre><code>The following notitifications are currently disabled: host: bar host: foo
  </code></pre>
  
  <p>I'm trying to figure out how to preserve the formatting that is present if I run the command manually.</p>
  
  <p>Things I've tried so far:</p>
  
  <pre><code>echo -e `cat datafile | awkscript` &gt; /tmp/tmpfile
  echo -e /tmp/tmpfile
  </code></pre>
  
  <p>I tried this because on my system (Solaris 5.10), using echo without the -e ignores standard escape sequences like \n . Didn't work. I checked the tmpfile, and it doesn't have any formatting in it, so the problem is happening when storing the output, not when printing it out.</p>
  
  <pre><code>BODY="$(awk -f awkscript datafile)"
  echo -e "$BODY"
  </code></pre>
  
  <p>I tried this because everything I could find, including some other questions here on stackoverflow said that the problem was that the shell would replace whitespace codes with spaces if it wasn't quoted. Didn't work.</p>
  
  <p>I've tried using printf instead of echo, using $(command) instead of `command`, and using a tempfile instead of a variable to store the output, but nothing seems to retain the formatting.</p>
  
  <p>What am I missing, or is there another way to do this which avoids this problem all together?</p>