Lazy Evaluation in Bash

前端 未结 3 1763
礼貌的吻别
礼貌的吻别 2020-12-16 14:49

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         


        
3条回答
  •  有刺的猬
    2020-12-16 15:20

    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"
    

提交回复
热议问题