Set env variable from BASH script

4.1k Views Asked by At

I need make something like

$ source /etc/environments # called in bash.sh script

Of course after script finished no changes apply to shell. I know this is tricky if because child process cant modify parent 'bash' process. But May be another way to do so?

2

There are 2 best solutions below

7
Andreas Louv On

As you have observed yourself a child process cannot set persistent environment variables. One of the usual work around are writing something like this to stdout:

% cat my_script
#!/bin/bash
echo "export MY_VAR=1234"

And then used in a command substitution:

eval "$(./my_script)"

An example of such script is dircolors

0
Barmar On

You should use

source bash.sh

Then it runs in the original shell instead of a child process.