How to replace environment variables in a file

1. Load environment from .env file

  • Let say we have a .env file:


  • Then run this script will load all environment variables to current shell terminal

    export $(grep -v '^#' .env | xargs)

  • You can also unset variables using below script

    unset $(grep -v '^#' .env | sed -E 's/(.*)=.*/\1/' | xargs)

2. Substitute all environment variables in a file

  • template.yml

    website: ${WEBSITE_URL}
    username: ${USERNAME}
    password: ${PASSWORD}

  • Run this script to substitute variable in the template.yml file and output to config.yml

    envsubst < template.yml > config.yml

  • Result is the config.yml

    username: hienhoang
    password: p@ssword