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
echo
instead of echoing the $NODE_ENV – Commorancy