Last active
November 13, 2023 14:01
-
-
Save a-magdy/0f6df1e0063efea9ab97bb9bc0c77bfa to your computer and use it in GitHub Desktop.
export vars from .env file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Example .env file | |
| VAR=something | |
| VAR2='one two three' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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 &;/')" | |
| #==================================================================================== |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment