Running shell script using .env file
39,382
Solution 1
You need to source the environment in the calling shell before starting the script:
source 'filename.env' && bash 'scriptname.sh'
In order to prevent polution of the environment of the calling shell you might run that in a sub shell:
(source 'filename.env' && bash 'scriptname.sh')
Solution 2
. ./filename.env
sh scriptname.sh
First command set the env. variables in the shell, second one will use it to execute itself.
Solution 3
Create the a file with name maybe run_with_env.sh
with below content
ENV_FILE="$1"
CMD=${@:2}
set -o allexport
source $ENV_FILE
set +o allexport
$CMD
Change the permission to 755
chmod 755 run_with_env.sh
Now run the bash file with below command
./run_with_env.sh filename.env sh scriptname.sh
Related videos on Youtube
Author by
Tony
Updated on November 03, 2021Comments
-
Tony over 2 years
I am fairly new to running scripts in UNIX/Linux. I have a .env file containing environment information and a .sh script containing folder creations etc for that environment.
How would I run the script on the environment contained in the .env file or how could I point the script to the target environment?
Would it be as easy as:
bash 'scriptname.sh' 'filename.env'
-
eltiare about 7 yearsI have my .env file set up as lines of
VAR=val
. This loaded the variables properly for me. -
phil294 over 4 yearsdont you also need
set -a
beforehand? Otherwise, the environment variables wont be exported and the scriptscriptname.sh
will not have access to any of those. Why is this upvoted / what am I missing? -
hek2mgl over 4 years@phil294 It depends. From reading the question it seemed to me that env.sh does already use
export
. If it's only setting variables but does not export them, thenset -a
might be an option. Well, it would export all variables from the calling script, not just those from env.sh, which might or might not be desired.