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 →
- Confirm:
ls -l /bin/sh(Ubuntu shows-> dash) and find bashisms withshellcheck -s sh script.shorcheckbashisms script.sh. - If Bash is guaranteed on every target, change the shebang to
#!/usr/bin/env bash. - If it must run in minimal images (Alpine, BusyBox), rewrite the bashisms in POSIX form instead.
- 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.
More on Scenarios: writing and hardening scripts
You inherit a 600-line `deploy.sh` with no error handling. It "sometimes half-deploys". Where do you start?IntermediateYou need a deploy script that humans and CI both call with `--env`, `--version` and `--dry-run`. How do you design its interface?BeginnerA maintenance script must run as the `deploy` user, never as root, because files it creates must be owned by `deploy`. How do you enforce that?BeginnerTen scripts in a repo each copy-paste their own `log`, `die`, retry and config loading. How do you fix this?IntermediateA script is run both by engineers and by cron. Cron logs are full of colour codes and the script sometimes hangs waiting for input. Fix it.BeginnerYour team decides all scripts must pass ShellCheck. The first run reports 400 findings across 60 scripts. How do you roll this out?Intermediate