How do I set a variable in the parent shell, from a subshell?
a=3
(a=4)
echo $a
The easiest way to set environment variables is to use the export command. Using export, your environment variable will be set for the current shell session. As a consequence, if you open another shell or if you restart your system, your environment variable won't be accessible anymore.
To make a variable available in a subshell (or any other subprogram of the shell), we have to “export” the variable with the export command.
To set an environment variable everytime, use the export command in the . bashrc file (or the appropriate initialization file for your shell). To set an environment variable from a script, use the export command in the script, and then source the script. If you execute the script it will not work.
Definition: A subshell is a child process launched by a shell (or shell script). A subshell is a separate instance of the command processor -- the shell that gives you the prompt at the console or in an xterm window.
The whole point of a subshell is that it doesn't affect the calling session. In bash a subshell is a child process, other shells differ but even then a variable setting in a subshell does not affect the caller. By definition.
Do you need a subshell? If you just need a group then use braces:
a=3 { a=4;} echo $a
gives 4
(be careful of the spaces in that one). Alternatively, write the variable value to stdout and capture it in the caller:
a=3 a=$(a=4;echo $a) echo $a
avoid using back-ticks ``, they are deprecated and can be difficult to read.
There is the gdb-bash-variable hack:
gdb --batch-silent -ex "attach $$" -ex 'set bind_variable("a", "4", 0)';
although that always sets a variable in the global scope, not just the parent scope
You don't. The subshell doesn't have access to its parent's environment. (At least within the abstraction that Bash provides. You could potentially try to use gdb
, or smash the stack, or whatnot, to gain such access clandestinely. I wouldn't recommend that, though.)
One alternative is for the subshell to write assignment statements to a temporary file for its parent to read:
a=3
(echo 'a=4' > tmp)
. tmp
rm tmp
echo "$a"
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