Bash script with .env file and commands

#bash#hugo

21 February 2025 | Updated on 22 February 2025

Create a bash script which loads and environment variables via an .env file and allows you to call different sub commands via functions.

Goal

Often times you need a small cli script to run commands for a project. Of course there are many special tools to do this kind of thing. But you can always use a simple bash shell script in case you do not want to install another program and add one more dependency to your project.

Example

Create the bash script file

  • in root of your project git repo
touch ctl.sh
chmod +x ctl.sh
  • this allows you to call the file as script directly
  • only add it to your git repo after changing chmod +x.

Edit the bash file

#!/usr/bin/env bash

# check if .env file exists
FILE=".env"
if [ -f "$FILE" ]; then
  echo "Found file: '${FILE}'. Will configure environment variables."
  set -o allexport; source .env; set +o allexport

# uncomment this in case you want to exit in case not .env file was found
# else
#   ###  Control will jump here if $FILE does NOT exists ###
#   echo -e "Error: ${FILE} not found. Can not continue.\ncreate some .env file with environment variables next to this bash file ctl.sh\nIn case you do not use any env just copy .env.sample or create a file .env with NOTUSED=1234"
#   exit 1
fi

set -eo pipefail

# ./ctl.sh hi <name>
function hi {
  NAME="$1"
  if [ -z "$1" ]; then
    echo "No argument supplied"
    exit
  fi
  echo "Hello $NAME :)"
}

# ./ctl.sh hugo:dev (start hugo development server)
function hugo:dev {
  hugo server --disableFastRender --cleanDestinationDir --printPathWarnings -D
}

# ./ctl.sh hugo:build (build hugo website for production)
function hugo:build {
  hugo --minify --cleanDestinationDir --printPathWarnings
}

function help {
  printf "%s <task> [args]\n\nTasks:\n" "${0}"

  # sometimes compgen is not available. then you just will not get a list of available commands.
  compgen -A function | grep -v "^_" | cat -n

  printf "\nExtended help:\n  Each task has comments for general usage\n"
}

TIMEFORMAT=$'\nTask completed in %3lR'
time "${@:-help}"

Use the script

Run command with argument

  • after the function name you can enter arguments (see function hi)
./ctl.sh run:hi Julius

Structure groups of commands with colon (:) punctuation mark

  • sometimes I group group functions like this
./ctl.sh hugo:dev
./ctl.sh hugo:build

Configure environment variables

  • you can set environment variables inside an .env file
    TEST_VAR="This is a test value"
    # TEST_VAR_2="hashtags are comments. so this variable will be ignored"
  • configured variables inside the .env file will be avaible when running the ctl.sh script

Additional resources


Related content