Cross-Platform Scripts
You wrote a handy script on your Mac, a teammate runs it on Windows, and it explodes. Or a script from a Windows colleague fails on a Linux server with a baffling \r: command not found. Most of these problems come from a short list of differences between the systems. This lesson goes through them and then shows the three practical ways to write one script that runs everywhere.
The differences that bite
| Topic | Windows | Linux & macOS |
|---|---|---|
| Line endings | CRLF (\r\n) |
LF (\n) |
| Path separator | \ (most tools accept / too) |
/ |
PATH list separator |
; |
: |
| Drive letters | C:\, D:\ |
one tree from / |
| Case of file names | case-insensitive (A.txt = a.txt) |
Linux: case-sensitive; macOS: insensitive by default |
| Executable | by extension (.exe, .bat, .ps1) |
by x permission + shebang |
| Default text encoding | UTF-8 in new tools; legacy code pages (1252, 437) in old ones | UTF-8 |
| Home folder | C:\Users\ada (%USERPROFILE%, $HOME) |
/home/ada, /Users/ada ($HOME) |
Line endings: CRLF vs LF
Each line of a text file ends with invisible control characters. Windows uses two (carriage return \r + line feed \n), Unix-like systems use one (\n). Most editors handle both, but shells don't: bash reads the \r as part of the command. Let's create a script with Windows line endings and watch it fail:
bash · try it yourself
printf '#!/bin/bash\r\necho "hello"\r\nls missing\r\n' > win.sh
od -c win.sh | head -n 2
bash win.sh 2>&1 | cat -A | head -n 2
echo "--- after removing the CRs ---"
sed -i 's/\r$//' win.sh
od -c win.sh | head -n 2
bash win.sh 2>&10000000 # ! / b i n / b a s h \r \n e c h
0000020 o " h e l l o " \r \n l s m i
hello^M$
ls: cannot access 'missing'