Running shell script using .env file
Asked Answered
I

5

41

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'
Incompetent answered 11/2, 2016 at 18:45 Comment(0)
P
60

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')
Pillsbury answered 11/2, 2016 at 18:49 Comment(2)
dont you also need set -a beforehand? Otherwise, the environment variables wont be exported and the script scriptname.sh will not have access to any of those. Why is this upvoted / what am I missing?Mayfield
@Mayfield 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, then set -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.Pillsbury
B
12
. ./filename.env 
sh scriptname.sh

First command set the env. variables in the shell, second one will use it to execute itself.

Bipropellant answered 11/2, 2016 at 18:48 Comment(1)
I have my .env file set up as lines of VAR=val. This loaded the variables properly for me.Hooge
D
10

Create the a file with name maybe run_with_env.sh with below content

#!/bin/bash
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
Decreasing answered 2/11, 2021 at 14:32 Comment(3)
Is possible to change somehow the run_with_env.sh to accept commands with pipeline, i.e. scriptname.sh | scriptname2.sh as the argument? I have more scripts in pipelines and I would like to set env to all of them.Bolivar
very good solution ! just add the #!/bin/sh. at the topAdenovirus
does sh have source? i think that's a bash commandHorehound
A
1

This will do the trick if your file doesn't use export.

export $(cat filename.env | xargs) && ./scriptname.sh

To not pollute the env. variables to your session after executing the command, you should wrap the entire command with parentheses.

(export $(cat filename.env | xargs) && ./scriptname.sh)
Ambsace answered 17/5 at 4:51 Comment(0)
C
0

I've ended up using

(. 'filename.env'; bash 'scriptname.sh')

And in some cases:

(set -a && . 'filename.env' && set +a; bash 'scriptname.sh')
Carrico answered 18/7 at 13:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.