Skip to content
CloudOps
Newsletter
All prompts
AI for Bash & Python Automation Difficulty: Beginner ClaudeChatGPT

Bash .env File Loader and Validator Prompt

Write a safe Bash loader that parses a .env file, validates required and typed variables, and exports them — without the security and quoting footguns of blindly sourcing untrusted env files.

Target user
Engineers wiring environment config into shell-based deploy and entrypoint scripts
Difficulty
Beginner
Tools
Claude, ChatGPT

The prompt

You are a shell scripting mentor teaching engineers to load `.env` config the safe way instead of `source .env`.

I will provide:
- A sample `.env` file (keys, comments, quoted values, maybe multiline)
- The list of required vars and their expected types (int, bool, URL, enum)
- Where the loader runs (container entrypoint, CI step, local dev)

Your job:

1. **Why not `source`** — explain the risks of `source .env` / `set -a; . .env`: arbitrary command execution from `$(...)` in values, clobbering existing shell vars and functions, and surprises from unquoted spaces. Establish that we parse explicitly instead.

2. **Safe parser** — read the file line by line, skip blank lines and `#` comments, split on the first `=` only, strip surrounding quotes, and reject keys that aren't `[A-Za-z_][A-Za-z0-9_]*`. Refuse to evaluate command substitutions in values. Show the loop with `IFS=` and `read -r` done correctly.

3. **Validation layer** — after loading, assert each required var is set and non-empty, and type-check: integers via a regex, booleans normalized to `true/false`, URLs and enums via patterns. Collect all failures and report them together, then exit non-zero — don't fail on the first one.

4. **Precedence** — already-set environment variables win over the file (so CI secrets override committed defaults); document and implement that order.

5. **Export scope** — show exporting into the current shell vs. running a child command with a scoped env (`env -i` style) so secrets don't leak into unrelated processes.

6. **Hygiene** — warn against committing real secrets, recommend `.env.example` with placeholder keys, and a `.gitignore` entry.

7. **Testing** — bats-style cases for missing required var, bad type, comment/quote handling, and the override-precedence rule.

Output as: (a) the `load_env` function, (b) the validation table for the sample file, (c) the precedence explanation, (d) the bats tests.

Bias toward: explicit parsing over sourcing, aggregating all validation errors, and never executing values.
Newsletter

Free: the DevOps AI Incident-Triage Cheat Sheet

Subscribe and we’ll send you the one-page cheat sheet — plus weekly AI prompts, automation ideas, and tool reviews for infrastructure engineers. One email a week. No spam, unsubscribe anytime.

  • AI Incident-Triage Cheat Sheet (PDF)
  • Access to 1,603 DevOps AI prompts
  • One practical workflow email per week