11

I need to set a system environment variable from a Bash script that would be available outside of the current scope. So you would normally export environment variables like this:

export MY_VAR=/opt/my_var

But I need the environment variable to be available at a system level though. Is this possible?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mbrevoort
  • 5,075
  • 6
  • 38
  • 48

5 Answers5

14

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

There two possibilities:

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

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

    eval `bash {script}`
    

    Or:

    eval "$(bash script.sh)"
    
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Douglas Leeder
  • 52,368
  • 9
  • 94
  • 137
6

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

In foo.sh, you have:

#!/bin/bash
echo MYVAR=abc123

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

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

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jeremy Cantrell
  • 26,392
  • 13
  • 55
  • 78
  • I was just trying to do that myself. I had eval and $(foo) except I left off the quotes around the argument to eval. Didn't work. Thanks for the syntax fix. – jmanning2k Dec 05 '08 at 22:38
1

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
nicerobot
  • 9,145
  • 6
  • 42
  • 44
1

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

env -i DISPLAY=:0 prog_that_need_xwindows arg1 arg2
koyaanisqatsi
  • 2,585
  • 2
  • 8
  • 15
1

You may want to use source instead of running 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 file but in same shell as the parent shell.
Possible downside in some rare cases : all variables regardless of explicit export or not will be exported. If some variables are required to be unset, unset those explicitly. Similarly, handle imported variables.

# Executable : exec.sh
export var="test"
invar="inside variable"
# --- #
unset invar
Himanshu Tanwar
  • 198
  • 1
  • 11