[ACCEPTED]-How to export a variable in Bash-sysadmin

Accepted answer
Score: 13

Not really - once you're running in a subprocess 4 you can't affect your parent.

There two possibilities:

  1. Source the 3 script rather than run it (see source .):

    source {script}
  2. Have the 2 script output the export commands, and eval 1 that:

    eval `bash {script}`


    eval "$(bash script.sh)"
Score: 6

This is the only way I know to do what you 8 want:

In foo.sh, you have:

echo MYVAR=abc123

And when you want 7 to get the value of the variable, you have 6 to do the following:

$ eval "$(foo.sh)"  # assuming foo.sh is in your $PATH
$ echo $MYVAR #==> abc123

Depending on what you 5 want to do, and how you want to do it, Douglas Leeder's suggestion about 4 using source could be used, but it will source 3 the whole file, functions and all. Using 2 eval, only the stuff that gets echoed will 1 be evaluated.

Score: 1

Set the variable in file /etc/profile (create the file 2 if needed). That will essentially make the 1 variable available to every Bash process.

Score: 1

When i am working under the root account and 3 wish for example to open an X executable 2 under a normal users running X.
I need to 1 set DISPLAY environment variable with...

env -i DISPLAY=:0 prog_that_need_xwindows arg1 arg2
Score: 0

You may want to use source instead of running 7 the executable directly:

# Executable : exec.sh
export var="test"
invar="inside variable"
source exec.sh
echo $var    # test
echo $invar  # inside variable

This will run the 6 file but in same shell as the parent shell.
Possible 5 downside in some rare cases : all variables 4 regardless of explicit export or not will 3 be exported. If some variables are required 2 to be unset, unset those explicitly. Similarly, handle 1 imported variables.

# Executable : exec.sh
export var="test"
invar="inside variable"
# --- #
unset invar

More Related questions