Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

interpolation - How to evaluate a shell variable each time it's used

Related to a similar problem I'm having: zsh not re-computing my shell prompt

Is there any way to define a shell variable such that its value is calculated each time its called?

for example if I do:

my_date="today is $(date)"

The value in my_date would be: today is Thu Aug 9 08:06:18 PDT 2012

but I want the date to be executed each time my_date is used. In the linked post, somebody recommended putting the value in single quotes:

my_date='today is $(date)'

but never evaluates anything, it just stays literally at $(date).

I'm using zsh 5.0.0

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That's not possible. Use a function instead:

my_date() {
    echo "today is $(date)"
}

# use it
echo "$(my_date)"

Note: This is bash syntax; your shell might use a slightly different syntax.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...