I'm writing a utility that needs to be able to set and use context. I'd like it to use environment variables in the shell so that it can remember what context it's currently in between invocations. Ideally, I'd like to set this environment variable from within the utility itself. Something like:
mytool set-context <context>
mytool do-stuff # Aware of <context>
I'd like this to behave like:
export MYTOOL_CONTEXT=<context>
mytool do-stuff # Aware of <context>
Now, it's not actually possible for a program to set environment variables in the environment of the calling shell (covered on SO here). However, that's the sort of behavior I want, and I'm looking for an approximation or workaround.
Some ideas I had in mind:
- Output the proper string, and expect the user to set the variable (assuming that the variable isn't simply set to
<context>
, but instead to some string derived from it). That would look something likeexport MYTOOL_CONTEXT=$(mytool get-context-var <context>)
. - Output the full command for setting it. That would look something like
$(mytool set-context <context>)
, where the output of the command is actually executed (and the output would be something likeexport MYTOOL_CONTEXT=<context>
). - Save to a temporary file whose name is based on the PID of the shell. This would work in most cases, but removing the file wouldn't happen automatically, so it would probably just lie around until reboot (ie, possibly forever on many machines).
Any other ideas? Thanks!
Note: The above examples use BASH syntax, but there are equivalents in most shells.
See Question&Answers more detail:os