1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Load Env Vars In Bash Script as a Unix TIL

This commit is contained in:
jbranchaud
2023-06-15 10:47:10 -05:00
parent fa20b1aa66
commit 4840461afa
2 changed files with 36 additions and 1 deletions

View File

@@ -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)

View File

@@ -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"}'
```