Search code examples
bashdeploymentscriptingpm2

using .env property in bash script


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

Solution

  • 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