Task
Create two files (release.txt, owner.txt) under a directory release-packages/northwind-api. The goal is to avoid typos by storing the path once in a variable.
Approach
Store the repeated path in a shell variable (TARGET_DIR), then reference it for both directory creation and file writes.
Solution
file.sh
#!/bin/bash
set -euo pipefail
TARGET_DIR=release-packages/northwind-api
mkdir -p "$TARGET_DIR"
echo 'release=2026.06.09' > "$TARGET_DIR/release.txt"
echo 'owner=platform' > "$TARGET_DIR/owner.txt"Now run the script using chmod +x file.sh, then ./file.sh.
Verification
$ cat release-packages/northwind-api/release.txt
release=2026.06.09
$ cat release-packages/northwind-api/owner.txt
owner=platformVerification isn’t just a formality. For example, a typo in the path or quoting can fail silently (e.g. create a wrongly named file) instead of throwing an error. So always confirm output rather than trusting the script ran correctly.
Gotchas & Best Practices
Quoting matters for variable substitution
- Double quotes
"$TARGET_DIR/release.txt"→ shell expands the variable correctly. - Single quotes
'$TARGET_DIR/release.txt'→ no expansion happens; the literal string$TARGET_DIRis used instead, breaking the script.
Memo: single quotes = literal string, double quotes = allows variable/command substitution.
echo and redirection
>overwrites the file each run;>>would append instead.echoadds a trailing newline. If exact byte content (no newline) is required, useprintf '%s' 'text' > fileinstead.
Variable naming
- All-caps names like
TARGET_DIRare a common shell convention for script-level variables. But avoid names that collide with real env vars (e.g.PATH,HOME).
Script safety
- Adding
set -euo pipefailat the top makes the script exit on errors, undefined variables, or failed pipe commands instead of silently continuing.