12

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?

5 Answers 5

15

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)"
    
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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.
1

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

1 Comment

Put a file to /etc/profile.d/ on modern distros.
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

1 Comment

The answer is still incomplete without eval statement as in accepted answer. The upvote is for a fair alternative to echo,
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.