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

倾然丶 夕夏残阳落幕 提交于 2019-11-29 14:31:57

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.

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.

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