Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export a shell variable to all sessions?

Tags:

bash

shell

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.

like image 604
user1293997 Avatar asked Feb 20 '13 22:02

user1293997


People also ask

How do I export a shell variable?

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.

How do I export all environment variables?

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.

How do I export an environment variable in Bash?

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.


2 Answers

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.

like image 192
that other guy Avatar answered Sep 21 '22 23:09

that other guy


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.

like image 33
cdarke Avatar answered Sep 19 '22 23:09

cdarke