[ACCEPTED]-How to export a variable in Bash-sysadmin
Not really - once you're running in a subprocess 4 you can't affect your parent.
There two possibilities:
This is the only way I know to do what you 8 want:
In foo.sh, you have:
#!/bin/bash echo MYVAR=abc123
And when you want 7 to get the value of the variable, you have 6 to do the following:
$ eval "$(foo.sh)" # assuming foo.sh is in your $PATH $ echo $MYVAR #==> abc123
Depending on what you 5 want to do, and how you want to do it, Douglas Leeder's suggestion about 4 using source could be used, but it will source 3 the whole file, functions and all. Using 2 eval, only the stuff that gets echoed will 1 be evaluated.
Set the variable in file /etc/profile (create the file 2 if needed). That will essentially make the 1 variable available to every Bash process.
When i am working under the
root account and 3 wish for example to open an X executable 2 under a normal users running X.
I need to 1 set
DISPLAY environment variable with...
env -i DISPLAY=:0 prog_that_need_xwindows arg1 arg2
You may want to use source instead of running 7 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 6 file but in same shell as the parent shell.
Possible 5 downside in some rare cases : all variables 4 regardless of explicit export or not will 3 be exported. If some variables are required 2 to be unset, unset those explicitly. Similarly, handle 1 imported variables.
# Executable : exec.sh export var="test" invar="inside variable" # --- # unset invar
More Related questions