I would like to know is there a way to export my shell variable to all sessions in the system (not only the current session). I'm not looking to set it in .bashrc file as the shell variable is a dynamic one it changes time to time.
You can use the export command to make local variables global. To make your local shell variables global automatically, export them in your . profile file. Note: Variables can be exported down to child shells but not exported up to parent shells.
To export a environment variable you run the export command while setting the variable. We can view a complete list of exported environment variables by running the export command without any arguments. To view all exported variables in the current shell you use the -p flag with export.
The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.
You can set up your sessions to keep rereading a file on disk by setting a trap on DEBUG in your .bashrc
:
trap 'source ~/.myvars' DEBUG
If you leave a terminal A open, run echo VAR=42 >> ~/.myvars
in terminal B, then switch back to terminal A and echo $VAR
, it'll "magically" be set.
You seem to misunderstand what export
does. All it does is to move a local variable into the environment block within the process (/proc/$$/environ
).
When a new process is created (a fork
) then the program data areas, including the environment block, are copied to the new process (actually they are initially shared, then copied when one writes). When a different program is run (execve), by default the environment block remains from the previous program. See also the env(1)
program.
So environment variables are normally inherited (copied) from their parent process. The only way to get a new environmnt variable into a running process is to use some sort of inoculation technique, as a debugger would do. Writing such a program is not an easy task, and I'm sure you could imagine the security implications.
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