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

烂漫一生 提交于 2019-11-28 08:26:51

问题


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


回答1:


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.




回答2:


You should have said about PS1 in the first case: prompt expansion is very different comparing to variable expansion. Guy that told you should be using PS1='$(command)' with single quotes was right, but he was missing one point: you must do

setopt promptsubst

to enable command substitution in prompt (and a few other substitutions as well).

It does not matter whether you set it before or after setting PS1, it should just happen before showing the prompt, option is checked every time PS1 expands to actual prompt.

For non-prompt variables @Aaron Digulla is completely right about you being unable to have variable that may change its value on subsequent evaluation. But in zsh you can additionally do two things: write a module (in C!) and use ${(%%)VAR} which will do prompt expansion on the given variable (note: it does respect promptsubst and two other prompt* options). There are more useful ${(...)} expansion flags.



来源:https://stackoverflow.com/questions/11886412/how-to-evaluate-a-shell-variable-each-time-its-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!