Friday, 31 July 2026

set -a to load .env

 ## 1. Why you need `set -a` to load `.env`


There's an important distinction in shells between **shell variables** and **environment variables**:


- **Shell variables** exist only in the current shell session. Child processes do **not** inherit them.

- **Environment variables** (exported variables) are inherited by every child process you spawn from that shell.


When you run `source .env`, the shell reads the file and executes lines like:


```sh

FOO=bar

API_KEY=secret

```


By default, these become **shell variables only** — they're set in your current shell, but if you then launch `uvicorn`, that child process will **not** see `FOO` or `API_KEY`, because they were never exported.


`set -a` (short for `set -o allexport`) changes that behavior: from that point on, **every** variable that gets created or modified is automatically marked for export. So the typical pattern is:


```sh

set -a

source .env

set +a

```


- `set -a` → turn on auto-export

- `source .env` → load the file; all vars are now exported to the environment

- `set +a` → turn it off again (so you don't accidentally export unrelated vars later)

No comments:

Post a Comment