Interview Scripting (Bash, Groovy)

How do you make a script portable across different shells and systems? [Advanced]

Answer

To make a script portable, I declare the intended shell, avoid non-portable features when targeting sh, check required commands, use POSIX-compatible options where possible, avoid hardcoded paths, handle GNU versus BSD differences, and test in the target environments.

Technical explanation

If the script requires Bash features, say so with the shebang and version checks instead of pretending it is portable sh.

Use command -v, mktemp, POSIX flags, and defensive quoting to reduce environment assumptions.

Containerized test runs are useful for validating behavior on Ubuntu, Alpine, RHEL-like images, and macOS where relevant.

Hands-on example

#!/usr/bin/env bash

set -euo pipefail

if (( BASH_VERSINFO[0] < 4 )); then

echo "Bash 4+ required" >&2

exit 2

fi

for cmd in awk sed curl; do

command -v "$cmd" >/dev/null || { echo "missing $cmd" >&2; exit 127; }

done

Preparing for an interview?

Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.

More Scripting (Bash, Groovy) interview questions

← All Scripting (Bash, Groovy) questions