Skip to content

Instantly share code, notes, and snippets.

@a-magdy
Last active November 13, 2023 14:01
Show Gist options
  • Select an option

  • Save a-magdy/0f6df1e0063efea9ab97bb9bc0c77bfa to your computer and use it in GitHub Desktop.

Select an option

Save a-magdy/0f6df1e0063efea9ab97bb9bc0c77bfa to your computer and use it in GitHub Desktop.
export vars from .env file
#!/bin/bash
# Use grep to validate each line using regex (clears out comments, empty lines and validates that each line is in the format of env vars)
# Then send it out to sed, to append export at the beginning of each line and ; at the end
# Then eval all
eval "$(grep -E '^[A-Za-z_][A-Za-z0-9_]*=.*' '.env' | sed 's/.*/export &;/')"
#====================================================================================
# Archive
#====================================================================================
# Simple (Works for most cases)
export $(grep -v '^#' .env | xargs)
# Complex (Works with vars that contain spaces
eval "$(cat '.env' | grep -v '^#' | grep -v '^$' | sed 's/.*/export &;/')"
# Complex with 1 grep regex that covers all cases (comments, empty lines & validates the <var_name=...> style)
eval "$(cat './.env.local' | grep -E '^[A-Za-z_][A-Za-z0-9_]*=.*' | sed 's/.*/export &;/')"
#====================================================================================
# Example .env file
VAR=something
VAR2='one two three'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment