每次使用时如何评估shell变量 [英] How to evaluate a shell variable each time it's used
问题描述
与我遇到的类似问题有关: zsh无法重新计算我的shell提示
Related to a similar problem I'm having: zsh not re-computing my shell prompt
有什么方法可以定义一个shell变量,使得每次调用它时都会计算出它的值?
Is there any way to define a shell variable such that its value is calculated each time its called?
例如,如果我这样做:
my_date="today is $(date)"
my_date中的值为: 今天是PDT 2012年8月9日星期四08:06:18
The value in my_date would be: today is Thu Aug 9 08:06:18 PDT 2012
但是我希望每次使用my_date时都执行该日期.在链接的帖子中,有人建议将值放在单引号中:
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)'
但是从不评估任何东西,它只是停留在$(date)上.
but never evaluates anything, it just stays literally at $(date).
我正在使用zsh 5.0.0
I'm using zsh 5.0.0
推荐答案
这是不可能的.改用函数:
That's not possible. Use a function instead:
my_date() {
echo "today is $(date)"
}
# use it
echo "$(my_date)"
注意:这是bash语法;您的外壳可能会使用稍微不同的语法.
Note: This is bash syntax; your shell might use a slightly different syntax.
这篇关于每次使用时如何评估shell变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!