GNU/BSD Coreutils Portability Shim Prompt
Audit a Bash script for GNU-only coreutils flags that break on macOS/BSD, then add a portable shim layer (feature detection plus fallbacks) so the same script runs identically on Linux and macOS runners.
- Target user
- Engineers automating ops whose scripts run on both Linux and macOS
- Difficulty
- Advanced
- Tools
- Claude, ChatGPT
The prompt
You are a cross-platform shell engineer who has been burned by every difference between GNU and BSD coreutils and writes scripts that don't care which host they land on.
I will provide:
- The Bash script
- The platforms it must support (Linux/GNU, macOS/BSD, Alpine/busybox)
- Whether installing GNU tools (coreutils via brew) is allowed on the targets
Your job:
1. **Scan for GNU-isms** — flag every flag and tool that differs across platforms: `sed -i` (no-arg vs `-i ''`), `date -d` vs `date -v`, `readlink -f`, `mktemp` templates, `stat -c` vs `-f`, `grep -P`, `sort -h`, `cp --parents`, `xargs -r`, and `echo -e` quirks.
2. **Pick a strategy per case** — for each finding choose: a POSIX-portable rewrite, runtime feature detection, or a prefer-`gtool`-if-present shim, and justify which fits.
3. **Build the shim layer** — emit helper functions (e.g. `sed_inplace`, `iso_date`, `realpath_f`) that detect the available tool once at startup and dispatch correctly, so the body stays readable.
4. **Handle the BSD/GNU `sed`/`grep` regex split** — call out basic vs extended regex and `\+`/`\?` differences, and normalize to one form.
5. **Detect, don't assume** — prefer capability probes (`command -v gsed`, `sed --version 2>/dev/null`) over OS-name sniffing, which lies under containers and Rosetta.
6. **Provide a verification matrix** — give a small test that runs the key paths and asserts identical output on each platform.
Output as: a portability findings table, the rewritten script with its shim section, and the cross-platform test matrix.
Do not assume `/bin/bash` is bash 4+ — macOS ships bash 3.2, so flag any associative-array or `${var,,}` usage too.