DEV Community

静亭雅苑
静亭雅苑

Posted on

One Shell Script, Three Operating Systems: What Actually Breaks

One Shell Script, Three Operating Systems: What Actually Breaks

The first bug report was one sentence long: "deploy doesn't work on my machine". The person reporting it was on Windows, had cloned the repository, and double-clicked the file the README told them to double-click. It opened a console window, printed two lines, and closed. On my MacBook the same file worked every day.

The script itself was fine. Everything around it was written for exactly one operating system, and nobody noticed because everyone who wrote it used the same one.

The failure was in the file, not the code

The second time it happened the error was visible, because the window stayed open long enough to read:

/bin/bash^M: bad interpreter: No such file or directory
Enter fullscreen mode Exit fullscreen mode

That ^M is a carriage return. The file had been edited on Windows at some point, saved with CRLF line endings, committed, and now every line of a shell script ended with a character the kernel does not expect. #!/bin/bash had quietly become #!/bin/bash\r.

Nothing in the code changed. The file simply traveled between two conventions and picked up a passenger.

The fix is not "be careful". The fix is to give line endings an owner, in the repository, once:

*.sh      text eol=lf
*.command text eol=lf
*.cmd     text eol=crlf
Enter fullscreen mode Exit fullscreen mode

With that file committed, a checkout on Windows produces CRLF only where a Windows program needs it, and LF everywhere a shell will read the file. It also makes the diff stable, which matters more than it sounds: before this, every Windows contributor's commit rewrote all line endings in the file and buried the real change.

One entry point, three front doors

The README promised "double-click to deploy". That promise needs three different implementations:

  • macOS: a .command file, which Finder will run in Terminal.
  • Windows: a .cmd file, because double-clicking a .sh file only opens an editor and asks what to do with it.
  • Any shell: the .sh file itself.

The .cmd wrapper does one job, and it is harder than it looks:

@echo off
where bash >nul 2>nul
if errorlevel 1 (
  set "BASH=%ProgramFiles%\Git\bin\bash.exe"
) else (
  set "BASH=bash"
)
"%BASH%" "%~dp0Deploy.sh" %*
Enter fullscreen mode Exit fullscreen mode

There is no bash on a stock Windows machine. There is one inside Git for Windows, at a path that depends on whether it was installed for all users or one user. And even when bash is on PATH for the interactive user, it may not be on PATH for the process that launched the script.

The wrapper is thirty lines of guessing. It is worth writing once, in one place, and never again.

The executable bit does not survive every filesystem

On macOS and Linux, ./deploy.sh requires the file mode to include execute. Git stores that bit — but only if the repository lives on a filesystem that can represent it. On an external drive formatted exFAT, permissions are not preserved: clone, and every script arrives as 644.

The symptom is not an error message about permissions, because most people invoke bash deploy.sh instead, which works. The symptom appears later, when someone else's documented command ./deploy.sh fails on a freshly cloned drive and everyone blames the script.

Two things help. First, document both invocations, so the working one is not folklore:

./Deploy.sh        # when the bit survived
bash Deploy.sh     # always works
Enter fullscreen mode Exit fullscreen mode

Second, have the commit path restore the bit, since it is cheap and idempotent:

chmod +x Deploy.sh Deploy.command Publish.sh
git update-index --chmod=+x Deploy.sh Deploy.command Publish.sh
Enter fullscreen mode Exit fullscreen mode

Doing it inside the deploy script rather than by hand means the mode gets repaired on every run, including the run where someone forgot.

Paths that only exist inside one shell

Git Bash on Windows reports paths like /c/Users/name/project or /d/work/project. Those are valid in the shell and meaningless to a native Windows binary. Pass one to node and you get a very confusing "cannot find module" for a path that ls happily lists.

The reliable way to get a path both worlds understand is to ask a program that runs in the native world:

ROOT="$(cd "$(dirname "$0")" && pwd -W 2>/dev/null || pwd)"
Enter fullscreen mode Exit fullscreen mode

pwd -W exists in Git Bash and returns D:/work/project. Under macOS or Linux the flag does not exist, so the fallback runs. One expression, two behaviors, no if [ "$(uname)" = ... ] scattered through the file.

For anything more involved, asking Node is clearer than testing for shells:

ROOT="$(node -p "process.cwd()")"
Enter fullscreen mode Exit fullscreen mode

Killing a dev server without lsof

A stop command looks trivial until you support three systems. lsof -ti:3000 | xargs kill is a one-liner on macOS and Linux, and a command that does not exist on Windows.

The portable version is not a one-liner, but it is short:

const { execSync } = require('child_process');
const port = Number(process.argv[2] || 3000);
const cmd = process.platform === 'win32'
  ? `netstat -ano -p tcp | findstr :${port}`
  : `lsof -nP -iTCP:${port} -sTCP:LISTEN`;
Enter fullscreen mode Exit fullscreen mode

The part worth copying is not the command selection. It is the ownership check before killing: read the process working directory, and refuse to terminate anything that is not running from this repository:

const cwd = process.platform === 'win32'
  ? execSync(`powershell -NoProfile -Command "(Get-Process -Id ${pid}).Path"`).toString().trim()
  : execSync(`lsof -a -p ${pid} -d cwd -Fn`).toString();
if (!cwd.includes(projectRoot)) return;
Enter fullscreen mode Exit fullscreen mode

A stop script that kills whatever holds port 3000 will eventually kill a database someone else is using. The check costs four lines.

Two commands, two grammars

sed -i is where portability arguments usually start. BSD sed treats the first argument after -i as a backup suffix, so sed -i 's/a/b/' file on macOS creates a file named b and leaves the original untouched. GNU sed does not. The portable form is the one nobody remembers:

sed -i '' 's/a/b/' file        # BSD
sed -i    's/a/b/' file        # GNU
Enter fullscreen mode Exit fullscreen mode

Rather than branch on the platform, write to a temporary file and move it:

sed 's/a/b/' "$file" > "$file.tmp" && mv "$file.tmp" "$file"
Enter fullscreen mode Exit fullscreen mode

Slower by milliseconds, correct everywhere, and readable by anyone who has not memorized both manual pages.

Dates have the same shape of problem. date -d '2026-12-01 10:00:00' +%s is GNU. BSD wants date -j -f '%Y-%m-%d %H:%M:%S' '2026-12-01 10:00:00' +%s. If the project already depends on Node, parsing in Node removes the branch entirely, and removes the assumption that the script is running under Git Bash rather than cmd.exe.

What actually fixed it

None of these were fixed by telling people to use the right terminal. The list that ended the bug reports:

  1. .gitattributes pinning line endings per file type, committed before anything else.
  2. One wrapper per operating system, each documented in the README next to the command it wraps.
  3. Execute bits restored by the deploy script itself, not by memory.
  4. Native paths obtained from a native program, never constructed by string concatenation.
  5. sed -i replaced with temp-file writes; date math moved into Node.
  6. A stop command that verifies ownership before killing.

The verification step is the one people skip: run every documented entry point on every supported system, once, before announcing support. Not the underlying script — the entry point, double-clicked, on a clean clone, on a machine that is not yours.

That is a twenty-minute check. It is also the only thing that separates "works on my machine" from "works".


Originally published on wuhuajin.com.

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

This is the post I wish existed the first time I watched a deploy script die on someone else's machine — and the CRLF story is the perfect opener, because the script itself was fine and the file was the bug. The .gitattributes fix is the kind of thing that looks obvious in hindsight and takes a team weeks to discover.

The part I keep coming back to is the ownership check before killing a process. Every stop script I've seen kills whatever holds the port, and yours is the first write-up I've read that names the actual risk: one day that port belongs to someone's database. That's a real insight, not just a portability trick.

One concrete next step I'd add to your six-point list: automate the verification step. The twenty-minute manual check — run every documented entry point on every supported system — is exactly what a CI matrix does well. A GitHub Actions job with macOS, Windows, and Linux runners that exercises each entry point the way a user would turns "works on my machine" into a green check on every pull request.

And a question on the .cmd wrapper: the thirty lines of guessing where bash lives — what happens when the machine has more than one candidate, like Git Bash plus a WSL install? Do you take the first one where finds, or is there a priority order that avoids picking the wrong bash?