using .env property in bash script
Asked Answered
C

2

7

I have a server application that has two deployments, one for the staging environment and another for the production environment. I have two individual scripts that are responsible for starting the processes. I would like to merge start_production.sh and start_staging.sh into start.sh by reading the environment file.

start_production.sh

#!/bin/bash
pm2 delete production
pm2 start "npm run build && npm run start:prod" --name production --log-date-format 'DD-MM HH:mm:ss.SSS'
pm2 logs

Inspecting the content, the only difference between the two scripts are the process name spaces which should always correspond to the environment file. Which would make it ideal to load the .env property NODE_ENV

.env

NODE_ENV=staging

ultimately I want to do something like

start.sh

#!/bin/bash
ENVIRONMENT={read NODE_ENV content of .env}
pm2 delete echo $ENVIRONMENT
pm2 start "npm run build && npm run start:prod" --name echo $ENVIRONMENT --log-date-format 'DD-MM HH:mm:ss.SSS'
pm2 logs

It might be pretty obvious that I am an absolute novice when it comes to bash scripting, so I would like for an as concrete as possible answer.

SOLUTION

I will provide a solution that is an aggregated solution based on the two current answers

start.sh

#!/bin/bash
source .env
ENVIRONMENT="$NODE_ENV"
if [ "$ENVIRONMENT" != "production" ] && [ "$ENVIRONMENT" != "staging" ]; then
    echo "improper .env NODE_ENV"
    exit
fi
pm2 delete "$ENVIRONMENT"
pm2 start "npm run build && npm run start:prod" --name "$ENVIRONMENT" --log-date-format 'DD-MM HH:mm:ss.SSS'
pm2 logs
Cates answered 5/6, 2021 at 15:5 Comment(0)
B
7

You could source the .env file. As the format KEY=value is compatible with how bash does its environment variables. So in your case, start.sh would be

#!/bin/bash
source .env

pm2 delete echo $NODE_ENV
pm2 start "npm run build && npm run start:prod" --name $NODE_ENV --log-date-format 'DD-MM HH:mm:ss.SSS'
pm2 logs
Blithering answered 5/6, 2021 at 15:13 Comment(3)
it creates a process with the name echo instead of echoing the $NODE_ENVCommorancy
If you remove the echo from the commands I will mark as answer :)Commorancy
Removed the echoBlithering
P
2

Akshit's advice on sourcing the .env file is good. I noticed a couple of other issues with your shell code.

The first thing worth noting is that it is a "best practice" to double quote your variable substitutions.

The bigger issue with your example code is extraneous echos. For instance,

pm2 delete echo $ENVIRONMENT

doesn't need the echo in there. The "echo" will become part of the command being run. It is not needed to the shell to replace the variable there.

Combining those two fixes we get

pm2 delete "$ENVIRONMENT"

which should work well.

Paternal answered 5/6, 2021 at 16:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.