Interview Prep/Shell Scripting/Scenarios: writing and hardening scripts

A script with `#!/bin/sh` works on CentOS but fails on Ubuntu with `Syntax error: "(" unexpected`. What is going on and what do you do?

BeginnerScenarioScenarios: writing and hardening scripts
Answer

Situation read → On CentOS/RHEL /bin/sh is Bash; on Debian/Ubuntu it is dash, which does not support arrays, [[ ]] or function syntax.

What I'd do →

  1. Confirm: ls -l /bin/sh (Ubuntu shows -> dash) and find bashisms with shellcheck -s sh script.sh or checkbashisms script.sh.
  2. If Bash is guaranteed on every target, change the shebang to #!/usr/bin/env bash.
  3. If it must run in minimal images (Alpine, BusyBox), rewrite the bashisms in POSIX form instead.
  4. Add ShellCheck to CI so the shebang and the code always agree.

Why → The shebang is a contract: it must name the shell the code is actually written for.

Interview tip → Mention that sh script.sh on the command line also forces dash, regardless of the shebang.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Scenarios: writing and hardening scripts