How to export a variable in bash

mbrevoort picture mbrevoort · Nov 20, 2008 · Viewed 19.1k times · Source

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?

Answer

Douglas Leeder picture Douglas Leeder · Nov 20, 2008

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.