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?
$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.
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.
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 .
$@ - 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.
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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With