简体   繁体   中英

How to export a variable in Bash

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?

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.

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.

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

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

...to every NEW bash process...

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM