views:

1975

answers:

3

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?

+1  A: 

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)"

EDIT: Corrected the second option to be eval rather than source. Opps.

Douglas Leeder
+2  A: 

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 have the variable available, you:

$ eval "$(foo.sh)"
$ 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.

Jeremy Cantrell
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
+1  A: 

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

nicerobot