How do I provide an environment to a script started like bash -c bla.sh

0

I noticed that e.g. ~/.bashrc is not sourced when starting a script with bash -c bla.sh. So how else can I provide environment variables? Preferably without explicitly setting them in the invocation.

rhall

Posted 2019-01-21T10:23:03.887

Reputation: 3

Answers

0

You can provide them on the command line (which you've stated you don't want):

MYVAR=hello ./bla.sh

You can set and export them first:

MYVAR=hello
export MYVAR
./bla.sh

or

export MYVAR=hello
./bla.sh

You can set up an "environment" file, and source this within your script (this is how ~/.bashrc is handled):

echo "MYVAR=hello" > test.env
./bla.sh

Within bla.sh:

source test.env
echo ${MYVAR}

Note that a . (period / dot) is an alias for source, so you could put . test.env in place of source text.env.

If you want to import your ~/.bashrc, then you could use source ~/.bashrc... but not that this will typically configure a number of things for a terminal / interactive environment - which is not how scripts run.

Attie

Posted 2019-01-21T10:23:03.887

Reputation: 14 841

Thank you. I chose to write a wrapper script, which sources the environment before running the actual script, like so: source test.env; $@. I didn't tell that bla.sh is just a placeholder for possibly many different scripts or commands. – rhall – 2019-01-21T23:40:51.277