0

I'm writing a bash script that first saves a text (with newline characters coming from grep), and then prints it later. For some reason, the line echo $TEXT prints just a single line. I took a look at this answer, and I believe I'm using the same thing (but with $() instead of backticks), but it's not working. Any ideas?

TEXT=$(grep Vacation vacations | grep Day)
echo "Counting days based on the following:"
echo "###############################################################"
echo $TEXT
echo "###############################################################"
Pedro Gordo
  • 1,825
  • 3
  • 21
  • 45

1 Answers1

1

You have to quote $TEXT, or else the newlines are treated like any other whitespace and simply serve as word boundaries when determining the arguments to echo.

echo "$TEXT"

However, it would be more efficient to simply run grep once you've already printed the header.

echo "Counting ..."
echo "####..."
grep Vacation vacations | grep Day
echo "####..."
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Doh, I read the other answer backward... Thanks! It works :) Any idea how to maintain `grep` highlighting when it's printed? – Pedro Gordo Jun 13 '18 at 19:51
  • 1
    @PedroGordo, that's a matter of `grep` detecting that output isn't to a TTY and disabling color highlighting. Read the manual for your version of grep; it may support something like `--color=always` (vs `--color=auto` depending on TTY detection for the toggle). – Charles Duffy Jun 13 '18 at 19:56