Oh... Probably title is not really easy to interpret. So let's describe it a little bit:
In .bashrc file I set PS1 to get custom prompt. In this prompt I need to have some additional info, which I get from other specific function. This function takes some time to exec so it is not cool to wait 1 sec after push enter in console. But I have idea to cached returned value from this specific function.
I need to check cache flag in every prompt print so I cant use variable, I must use function in printing prompt, because sourceing .bashrc is only one times, but if I pass function to PS1 it will be execed every time.
prompt_fun(){
export CACHE_YES=1
export PROMPT_CACHE="Something"
echo "$PROMPT_CACHE"
#in real case here will be checking if cache is turned on.
#If yes, we use cached value from exported variable in first time.
#If no, we exec specific function and export values to env variables.
}
PS1="$(prompt_fun): "`
Of course, variable CACHE_YES and PROMPT_CACHE are not set in console, so I am unable to control caching be changing CACHE_YES. I know when cache should change so I can type in console to change CACHE_YES=0 but my script don't rechange it to CACHE_YES=1 after cache new values.
How to make that export in prompt_fun have global effect?
The short answer is, you can't. Since prompt_fun is called in a command substitution, any changes made to variables in that subshell disappear when the subshell exits.
Instead, you'll want to set the value of PS1 inside prompt_fun, then call prompt_fun from the value of PROMPT_COMMAND, as the value of that parameter is executed in the current shell context prior to each prompt being displayed.
prompt_fun () {
if [[ -z $CACHE ]]; then
# Set value of $CACHE
fi
PS1=something
PS1+=something_else
PS1+=$CACHE
PS1+=final_value
}
PROMPT_COMMAND='prompt_fun' # Yes, single quotes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With