Useful bash command to use with environment variable

Useful bash command to use with environment variable

My practical use when I want to store scripts in a git repository but do not want to expose secret key (password, ...etc) is storing secured data in .env file.

It is also useful to make a file named .env.sample, add it to the repo to make others understand the environment file format.

Obviously, .env should be included in .gitignore

Here are some useful commands I usually use

  • To get dir path of the executing script (like os.path.dirname(os.path.abspath(__file__)) in Python)
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
  • To read the value from .env and store them to variables
 $(grep -v '^\(#\|\s*$\)' ${DIR}/.env | xargs -0)
  • You may want to check if .env file exists and notifies your dev to make them
if [ ! -f ${DIR}/.env ]; then
	echo '.env does not exist. check .env.example for sample configuration'
	exit 1
  • To make sure your script is executed with bash, and put this line to the top of the script
#!/usr/bin/env bash
  • To make your script executable, run the following command
chmod a+x
Buy Me A Coffee