Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...