23

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.

3
  • Why bend over backwards with backticks? Just do text='line1<newline>line2' (so the assignment spans two literal lines of text), or text=$'line1\nline2' if you are happy with restricted portability. Commented Sep 18, 2012 at 0:23
  • 1
    with bash, the way to get that text into a variable is text=$'line1\nline2' Commented Sep 18, 2012 at 0: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
    Commented Sep 18, 2012 at 0:32

2 Answers 2

53

Same solution as always.

echo "$text"
3
  • 3
    sorry, how is this different from echo $text?
    – inger
    Commented Sep 17, 2012 at 23:19
  • 8
    There are double quotes, which inhibits word splitting in bash. Commented Sep 17, 2012 at 23:22
  • Here's another clue about word splitting: python -c "import sys; print sys.argv" $text produces: ['-c', 'line1', 'line2'], while if we double-quote the final argument, we get ['-c', 'line1\nline2']. Commented Dec 10, 2013 at 7:19
5
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.

2
  • 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
    Commented Sep 17, 2012 at 23:38
  • While this might work in general, in Docker, RUN echo -e blah produces "-e blah" Commented Nov 7, 2021 at 20:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.