bashlazy-evaluation

Lazy Evaluation in Bash


Is there more elegant way of doing lazy evaluation than the following:

pattern='$x and $y'
x=1
y=2
eval "echo $pattern"

results:

1 and 2

It works but eval "echo ..." just feels sloppy and may be insecure in some way. Is there a better way to do this in Bash?


Solution

  • You can use the command envsubst from gettext, for example:

    $ pattern='x=$x and y=$y'
    $ x=1 y=2 envsubst <<< $pattern
    x=1 and y=2