22

In Bash (or other shells) how can I print an environment variable which has a multi-line value?

text='line1
line2'

I know a simple usual echo $text won't work out of the box. Would some $IFS tweak help?

My current workaround is something like ruby -e 'print ENV["text"]'. Can this be done in pure shell? I was wondering if env command would take an unresolved var name but it does not seem to.

Zombo
  • 1
  • 62
  • 391
  • 407
inger
  • 19,574
  • 9
  • 49
  • 54
  • Why bend over backwards with backticks? Just do `text='line1line2'` (so the assignment spans two literal lines of text), or `text=$'line1\nline2'` if you are happy with restricted portability. – William Pursell Sep 18 '12 at 00:23
  • 1
    with bash, the way to get that text into a variable is `text=$'line1\nline2'` – glenn jackman Sep 18 '12 at 00:25
  • @WilliamPursell I knew it was simpler than that I tried heredoc first but that didn't work..but of course a plain multiline string is simpler..it's just very late to refresh my bash memories. thanks. – inger Sep 18 '12 at 00:32

2 Answers2

51

Same solution as always.

echo "$text"
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
4
export TEST="A\nB\nC"
echo $TEST

gives output:

A\nB\nC

but:

echo -e $TEST
A
B
C

So, the answer seems to be the '-e' parameter to echo, assuming that I understand your question correctly.

sirgeorge
  • 6,331
  • 1
  • 28
  • 33
  • 3
    Thanks, that's nice indeed.. however in my scenario the var contains a genuine LF char rather than the escape sequence. Clarifying the question now. – inger Sep 17 '12 at 23:38
  • While this might work in general, in Docker, RUN echo -e blah produces "-e blah" – Jeremy Woodland Nov 07 '21 at 20:21