0

We know that 'eval' can do evil things: Like execute code. I need a way in BASH to be able to identify in a string of characters where an environment variable is used, and ultimately replace it with its actual value.

e.g. This is a very simple example of something much more complex.
File "x.dat" contains:

$MYDIR/file.txt

Environment

export MYDIR=/tmp/somefolder

Script "x.sh"

...
fileToProcess=$(cat x.dat)
realFileToProcess=$(eval echo $fileToProcess)
echo $realFileToProcess
...

Keep in mind that referenced environment variables in a string can also be:

${MYDIR}_txt
$MYDIR-txt
${MYDIR:0:3}:txt
${MYDIR:5}.txt
Jeff M Palmer
  • 29
  • 1
  • 7

1 Answers1

0

Not an aswer yet but some remarks about the question.

It seems what you need is not variable expansion but token replacement in a template, depending the use case printf may be sufficient.

variable expansion depends also on context for example following are not replaced:

# single quotes
echo '${MYDIR}'

# ANSI-C quotes
echo $'${MYDIR}'

# heredoc with end marker enclosed between single quotes
cat << 'END'
${MYDIR}
END

Should be noted also that a variable expansion may execute arbitrary code:

echo ${X[`echo hi >&2`]}
Nahuel Fouilleul
  • 18,726
  • 2
  • 31
  • 36