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

后端 未结 2 500
情歌与酒
情歌与酒 2020-12-21 04:12

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 tim

相关标签:
2条回答
  • 2020-12-21 04:41

    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.

    0 讨论(0)
  • 2020-12-21 04:44

    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.

    0 讨论(0)
提交回复
热议问题