Doing this directly in .bash_profile
(or .bashrc
or any similar file) would require managing the relevant part of the file while leaving other parts intact. This problem has a simple generic solution:
- Do not change
.bash_profile
over and over again.
- Create like
~/.my_tokens
which you would change, append to, possibly rewrite entirely.
Source the new file from .bash_profile
. This is the only (and one-time) change you do directly in .bash_profile
:
. ~/.my_tokens
It's now up to you how you manage the new file. If the file contains just few tokens, the easiest way to update may be to overwrite it entirely.
And in case of changes it may be enough to source only .my_tokens
again, not the whole .bash_profile
.
You can gather many such files in a directory and source them all:
# ~/my_extensions is a directory with no subdirectories
for f in ~/my_extensions/*; do
. "$f"
done
The general idea is to separate "dynamic" tokens from your semi-static .bash_profile
.
The idea of updating these tokens in every existing Bash session every 30 minutes or so seems inelegant at least. Consider reading them on-demand (not via .bash_profile
at all). Let's say foo
is some external command that needs these tokens. Create a wrapper function:
foo() ( . ~/my_tokens; command foo "$@" )
Now if you call foo
, the function will load current tokens and call the real foo
utility. Note the entire function body is in a subshell, so the tokens are not available to the current shell (unless you have separately sourced the file). To source the tokens in the current shell instead, define the function like this:
foo() { . ~/my_tokens; command foo "$@"; }
Note: for global tokens you should use some path outside any user's directory; example for Linux: /run/foo_tokens
.
An atomic update of ~/my_tokens
(or /run/foo_tokens
or any other file) can be done with mv
. You create a temporary file on the same filesystem, fill it with data, then overwrite the old version in one final step:
mv ~/temp_tokens ~/my_tokens
This guarantees any access to ~/my_tokens
gets either the old version or the new one in its entirety. If you updated the file in place, it would be possible to read it as incomplete or partially updated; you certainly don't want this.