Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 897
User1 Avatar asked May 24 '10 22:05

User1


People also ask

What does [- Z $1 mean in Bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

What is $@ in Bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc.

What is f flag in Bash?

The “[ -f ~/. bashrc]” is known as a test command in bash. This command, which includes the “-f” expression, will check if the ~/. bashrc file exists (i.e. the file .

What is $$ variable in Bash?

$@ - All the arguments supplied to the Bash script. $? - The exit status of the most recently run process. $$ - The process ID of the current script. $USER - The username of the user running the script.


2 Answers

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
like image 134
tokland Avatar answered Sep 25 '22 23:09

tokland


One safe possibility is to use a function:

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

That's all. Then use as follows:

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 scope):

x=1 y=1 expand_pattern
echo "$pattern"
like image 28
gniourf_gniourf Avatar answered Sep 26 '22 23:09

gniourf_gniourf