From 4840461afaa9ebb0bdfd6d24f68d34c2b95e649b Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 15 Jun 2023 10:47:10 -0500 Subject: [PATCH] Add Load Env Vars In Bash Script as a Unix TIL --- README.md | 3 ++- unix/load-env-vars-in-bash-script.md | 34 ++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 unix/load-env-vars-in-bash-script.md diff --git a/README.md b/README.md index 8aa09d8..b55ea72 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1311 TILs and counting..._ +_1312 TILs and counting..._ --- @@ -1292,6 +1292,7 @@ _1311 TILs and counting..._ - [List Stats For A File](unix/list-stats-for-a-file.md) - [List The Available JDKs](unix/list-the-available-jdks.md) - [List The Stack Of Remembered Directories](unix/list-the-stack-of-remembered-directories.md) +- [Load Env Vars In Bash Script](unix/load-env-vars-in-bash-script.md) - [Map A Domain To localhost](unix/map-a-domain-to-localhost.md) - [Negative Look-Ahead Search With ripgrep](unix/negative-look-ahead-search-with-ripgrep.md) - [Occupy A Local Port With Netcat](unix/occupy-a-local-port-with-netcat.md) diff --git a/unix/load-env-vars-in-bash-script.md b/unix/load-env-vars-in-bash-script.md new file mode 100644 index 0000000..934102f --- /dev/null +++ b/unix/load-env-vars-in-bash-script.md @@ -0,0 +1,34 @@ +# Load Env Vars In Bash Script + +I have a file with environment variables in my current directory named +something like `.env.local`. I want to load those variabls into my environment +in the context of a bash script. That can be accomplished by exporting them at +the beginning of the script with a line like this: + +```bash +export $(egrep -v '^#' .env.local | xargs) +``` + +This uses `egrep` with the `-v '^#'` inverted match pattern to excluded any +comment lines. Then `xargs` is going to remove any excess whitespace and echo +the sequence env var entries. All of which will be the argument passed to +`export` which adds them to the environment. + +Here is an example of using it in a script that uses one of those secret env +var values as a bearer token in a cURL request. + +```bash +#!/bin/bash + +# Load environment variables from .env.local file +export $(egrep -v '^#' .env.local | xargs) + +# Now you can use the environment variable in your CURL command +curl -L \ + -X POST \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: Bearer $GITHUB_ACCESS_TOKEN"\ + -H "X-GitHub-Api-Version: 2022-11-28" \ + https://api.github.com/repos/jbranchaud/github-actions-experiment/actions/workflows/playwright.yml/dispatches \ + -d '{"ref":"main"}' +```