Tony
Tony

Reputation: 721

Running shell script using .env file

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'

Upvotes: 42

Views: 83497

Answers (5)

Konard
Konard

Reputation: 3034

I've ended up using

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

And in some cases:

(set -a && . 'filename.env' && set +a; bash 'scriptname.sh')

Upvotes: 0

Rok Povsic
Rok Povsic

Reputation: 4935

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)

Upvotes: 2

Anand Tripathi
Anand Tripathi

Reputation: 16166

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

Upvotes: 12

hek2mgl
hek2mgl

Reputation: 158140

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')

Upvotes: 65

Steephen
Steephen

Reputation: 15824

. ./filename.env 
sh scriptname.sh

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

Upvotes: 12

Related Questions