0

The easiest way to describe the problem is to demonstrate it.

The goal is to store a command that upon execution would properly display the content of a variable CONTENT, including the line breaks.

If we are to add -x to the #! it would be clear the \n gets swallowed during the interpolation $display_cmd during execution even though it seems to be assigned properly. This in turn means that using printf instead of echo has the same result.

I have a workaround using cat and a HERE doc, but I would strongly prefer not to use it. The reason being that with HERE doc the EOF marker needs to start on the first column, which at some point someone is going to decide to make align with the rest of the code breaking the workaround.

Is here a way to accomplish what I want without using a HERE doc?

#!/bin/bash 

CONTENT=$(cat << EOF
Untrusted first line
Untrusted second line
EOF
)

# This will work

echo "CONTENT variable will print on two different lines"
echo

echo -e "$CONTENT"

# This won't work
# Create a command

echo "And this will display content on a single line:"
echo 

display_cmd="echo -e \"${CONTENT}\""

$display_cmd
  • 2
    "Variables hold data. Functions hold code. Don't put code inside variables!", from . I recommend you read it carefully and then reconsider your question. – Quasímodo Mar 13 '20 at 16:57
  • 1
    Note that while I closed this as duplicative of a question whose accepted answer suggests using `eval`, you **absolutely should not use `eval`**. Instead, follow the advice given in the BashFAQ #50 link above. – Charles Duffy Mar 13 '20 at 17:00
  • ...if you *were* to use `eval`, you'd need to change your code: `display_cmd="echo \"\${CONTENT}\""` (the critical thing is that we're putting a backslash before the `$`, so your untrusted content isn't substituted into code; the other thing is that we're no longer depending on `echo -e`, which is deeply unreliable for reasons detailed in https://unix.stackexchange.com/a/65819/3113). But then someone reading that code would need to get into the weeds to make sure the quoting was right, and folks maintaining it would need to take great care in the future to avoid serious security bugs. – Charles Duffy Mar 13 '20 at 17:02
  • (see [BashFAQ #48](http://mywiki.wooledge.org/BashFAQ/048) for more on why `eval` use is dangerous). – Charles Duffy Mar 13 '20 at 17:03

0 Answers0