Lazy score in Bash

Is there a more elegant way to lazy evaluate than the following:

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

results:

 1 and 2

This works, but eval "echo ..." just feels messy and might be somehow insecure. Is there a better way to do this in bash?

+11
bash lazy-evaluation
May 24 '10 at 22:16
source share
3 answers

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

 $ pattern='$x and $y' $ x=1 y=2 envsubst <<< $pattern 1 and 2 
+5
Jun 02 '10 at 15:45
source share

One safe option is to use the function:

 expand_pattern() { pattern="$x and $y" } 

It's all. Then use the following:

 x=1 y=1 expand_pattern echo "$pattern" 

You can even use x and y as environment variables (so that they are not set in the main area):

 x=1 y=1 expand_pattern echo "$pattern" 
+4
Feb 23 '18 at 22:29
source share

You are right, eval is a security risk in this case. Here is one possible way:

 pattern='The $a is $b when the $z is $x $c $g.' # simulated input from user (use "read") unset results for word in $pattern do case $word in \$a) results+=($(some_command)) # add output of some_command to array (output is "werewolf" ;; \$b) results+=($(echo "active")) ;; \$c) results+=($(echo "and")) ;; \$g) results+=($(echo "the sky is clear")) ;; \$x) results+=($(echo "full")) ;; \$z) results+=($(echo "moon")) ;; *) do_something # count the non-vars, do a no-op, twiddle thumbs # perhaps even sanitize %placeholders, terminal control characters, other unwanted stuff that the user might try to slip in ;; esac done pattern=${pattern//\$[abcgxz]/%s} # replace the vars with printf string placeholders printf "$pattern\n" "${results[@]}" # output the values of the vars using the pattern printf -v sentence "$pattern\n" "${results[@]}" # put it into a variable called "sentence" instead of actually printing it 

The result will be β€œA werewolf is active when the moon is full and the sky is clear.” The program itself, if the pattern is equal to '$ x $ z outside $ c $ g, therefore $ a must be $ b.' then the output will be "The full moon will disappear and the sky will become clear, so the werewolf must be active."

0
May 25 '10 at 7:48 a.m.
source share



All Articles