Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 914
D.C. Avatar asked Dec 16 '22 20:12

D.C.


2 Answers

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.

like image 166
Aaron Digulla Avatar answered Dec 29 '22 10:12

Aaron Digulla


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.

like image 39
ZyX Avatar answered Dec 29 '22 12:12

ZyX