Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a parent shell's variable from a subshell

How do I set a variable in the parent shell, from a subshell?

a=3
(a=4)
echo $a
like image 537
Matt Joiner Avatar asked Mar 21 '13 07:03

Matt Joiner


People also ask

How do you set an environment variable that is accessible from subshell?

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.

What is the command used to make variables available to subshells?

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.

How do you make a shell variable into an environment variable?

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.

Is a subshell a child process?

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.


3 Answers

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.

like image 105
cdarke Avatar answered Sep 20 '22 13:09

cdarke


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

like image 43
BeniBela Avatar answered Sep 17 '22 13:09

BeniBela


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"
like image 26
ruakh Avatar answered Sep 20 '22 13:09

ruakh