1
NL=$'\n'
CMD=""
CMD="$CMD echo Hello ; $NL"
CMD="$CMD echo World ; $NL"
$CMD

The above code gives the following output, the echo globing everything after it.

Hello ; echo World ;

Neither the new line character nor the semicolon does work here. What is going wrong?

melpomene
  • 84,125
  • 8
  • 85
  • 148
  • 3
    http://mywiki.wooledge.org/BashFAQ/050 – melpomene Aug 29 '17 at 06:09
  • 2
    Look at the link @melpomene gave you. Why do you want to do it? If you don't mind playing dangerously, explore `eval $CMD` and variants on that theme (`eval "$CMD"`, …). Then decide to do whatever it is you are trying to do (an [XY Problem](http://mywiki.wooledge.org/XyProblem)?) a different way. – Jonathan Leffler Aug 29 '17 at 06:32
  • 1
    Assuming you went the `eval` route, you don't need newlines at all; a semicolon by itself separates two commands just fine. When `$CMD` is expanded without quotes, the newlines are just discarded anyway, but the semicolons are treated as arguments to the `echo` command (that is, the expansion is not reparsed). – chepner Aug 29 '17 at 12:46

1 Answers1

-2

For enabling interpretation of backslash escapes you have to add -e flag to echo.

:/$ NL='\n'

Putting line feed into NL variable.

:/$ CMD=""

Setting CMD to empty string.

:/$ CMD="$CMD echo Hello ; $NL"

Resetting CMD, since old CMD is "" then new is " echo Hello ; \n"

:/$ CMD="$CMD echo World ; $NL"

Resetting CMD, since old CMD is " echo Hello ; \n" then new is " echo Hello ; \n echo World ; \n"

:/$ echo -e $CMD
echo Hello ; 
 echo World ; 
metamorphling
  • 369
  • 3
  • 9