Delayed variable expansion in bash

592 views Asked by At

I have a scenario where I echo multiple lines and pipe them to a translator, like this:

echo -n '
$error This is an error$defaults
$fatal THIS IS FATAL ERROR$defaults
 This is normal text
' | translate ansi

echo -n '
$error This is an error$defaults
$fatal THIS IS FATAL ERROR$defaults
 This is normal text
' | translate html

I first used sed to replace ansi with html codes, but due to the obvious speed issues, I would like to do something like this:

input="$(cat)"
if [ "$1" == ansi ]
then
    error="[1m[31m"
    fatal="[0m[30m[41m"
    defaults="[0m"
elif [ "$1" == html ]
then
    error='<span class="error">'
    fatal='<span class="fatal">'
    defaults='</span>'
fi
eval "echo "$input""

But the output is in a single line. I experimented with ${} and cat << tricks, but none of the experiments gave me the desired output.

1

There are 1 answers

2
NeronLeVelu On BEST ANSWER
eval "echo \"$( echo "${input}" )\""

but why not directly a sed (here using your variable name and content by substitution

cat > | sed "s/\$error/${error}/g;s/\$fatal/${fatal}/g;s#\$defaults#${defaults}#g'