TExcelTAD
Home › Terminal & Command Line › Cross-Platform Scripts

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>&1
0000000   #   !   /   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'
  

\r': No such file or directory$
--- after removing the CRs ---
0000000   #   !   /   b   i   n   /   b   a   s   h  \n   e   c   h   o
0000020       "   h   e   l   l   o   "  \n   l   s       m   i   s   s
hello
ls: cannot access 'missing': No such file or directory

Before the conversion, echo printed hello\r (shown by cat -A as ^M), and ls looked for a file literally named missing\r. After stripping the \r at the end of each line with sed, the script behaves. The dedicated tools dos2unix and unix2dos (installable everywhere, included in Git Bash) convert files in both directions. The fix in practice:

  • Set your editor to LF for scripts (VS Code shows CRLF/LF in the status bar; click to change).
  • In Git, add a .gitattributes file so the repository decides, not each person's settings:
text
*.sh   text eol=lf
*.bat  text eol=crlf
*.cmd  text eol=crlf
*.ps1  text eol=crlf

Batch files are the opposite case: CMD can misread labels and goto jumps in a .bat file saved with LF only, so keep them CRLF. PowerShell accepts both. See .gitattributes for details.

Paths and separators

Hard-coded paths like C:\Users\ada\data or /home/ada/data break on the other system. Build paths from parts with the language's own tools instead:

powershell · try it yourself
$base = Join-Path $HOME 'projects'
$file = Join-Path $base 'app' 'config.json'
"separator: $([IO.Path]::DirectorySeparatorChar)"
"PATH list separator: $([IO.Path]::PathSeparator)"
$file.Replace($HOME, '~')
"on Windows? $IsWindows  Linux? $IsLinux  macOS? $IsMacOS"
separator: /
PATH list separator: :
~/projects/app/config.json
on Windows? False  Linux? True  macOS? False

The playground runs PowerShell 7 on Linux, so it prints / and :. The same script on Windows prints \ and ;, and builds C:\Users\ada\projects\app\config.json, with no change to the code. $IsWindows, $IsLinux and $IsMacOS let you branch when you must.

Python's pathlib does the same, and can even show Windows-style paths on any OS:

python · try it yourself
from pathlib import Path, PurePosixPath, PureWindowsPath

parts = ("projects", "app", "config.json")
print(PurePosixPath("/home/ada", *parts))
print(PureWindowsPath("C:/Users/ada", *parts))
p = PureWindowsPath(r"C:\Users\ada\report.final.PDF")
print(p.name, "|", p.stem, "|", p.suffix.lower(), "|", p.parent)
print(Path("data") / "2026" / "sales.csv")
/home/ada/projects/app/config.json
C:\Users\ada\projects\app\config.json
report.final.PDF | report.final | .pdf | C:\Users\ada
data/2026/sales.csv

Two more path rules: always quote paths, because folders like C:\Program Files and ~/My Documents contain spaces, and never rely on case: Readme.md and README.md are the same file on Windows and macOS but two files on Linux.

Text encodings

An encoding maps characters to bytes. Today the answer is almost always UTF-8, but Windows tools have a legacy: Windows PowerShell 5.1 writes UTF-16 with > and Out-File, and CMD uses an old code page unless you switch with chcp 65001. The same word can become very different bytes:

bash · try it yourself
printf 'café' > utf8.txt
iconv -f UTF-8 -t UTF-16LE utf8.txt > utf16.txt
iconv -f UTF-8 -t CP1252 utf8.txt > cp1252.txt
for f in utf8.txt utf16.txt cp1252.txt; do
  printf '%-11s %2d bytes: ' "$f" "$(wc -c < "$f")"
  od -An -tx1 "$f" | tr -s ' '
done
utf8.txt     5 bytes:  63 61 66 c3 a9
utf16.txt    8 bytes:  63 00 61 00 66 00 e9 00
cp1252.txt   4 bytes:  63 61 66 e9

If someone opens the CP1252 file as UTF-8, é turns into a �; open UTF-8 as CP1252 and you get café. Rules of thumb: save scripts and data as UTF-8, use -Encoding utf8 in Windows PowerShell 5.1 (PowerShell 7 defaults to UTF-8 already), and in Python always pass encoding="utf-8" to open().

Strategy 1: PowerShell 7 everywhere

PowerShell 7 (pwsh) runs on Windows, macOS and Linux, and its cmdlets (Get-ChildItem, Copy-Item, Join-Path, ConvertFrom-Json) behave the same on all three. A .ps1 script that avoids Windows-only features (registry, WMI, C:\ paths) is portable. Install it with winget install Microsoft.PowerShell, brew install powershell or your Linux package manager, and start scripts on Unix with #!/usr/bin/env pwsh.

Strategy 2: bash everywhere

bash is on every Linux and macOS (macOS's is the old 3.2; zsh runs most simple bash scripts too). On Windows you can get bash in two ways:

  • Git Bash, installed with Git for Windows: a bash with the common GNU tools, working on your Windows files. Paths look like /c/Users/ada. Great for small scripts and Git hooks.
  • WSL: a real Linux system inside Windows (see WSL: Linux on Windows). Best for serious development.

Stick to POSIX features and GNU/BSD-compatible options (see BSD vs GNU Tools) when a script must also run on macOS.

Strategy 3: a real programming language

When a script grows beyond a page, or must handle paths, JSON and errors carefully on every OS, use Python (or Node.js). The standard library hides the OS differences: pathlib, shutil.copy, subprocess.run, os.environ, platform.system():

python · try it yourself
import json, os, shutil, tempfile
from pathlib import Path

root = Path(tempfile.mkdtemp()) / "myapp"
(root / "src").mkdir(parents=True)
(root / "config.json").write_text(json.dumps({"name": "myapp", "debug": False}), encoding="utf-8")
shutil.copy(root / "config.json", root / "src" / "config.backup.json")
for path in sorted(root.rglob("*")):
    kind = "dir " if path.is_dir() else "file"
    print(kind, path.relative_to(root).as_posix())
print("HOME is set:", "HOME" in os.environ or "USERPROFILE" in os.environ)
file config.json
dir  src
file src/config.backup.json
HOME is set: True

The same file runs unchanged with python on Windows and python3 on macOS and Linux.

Which one?

Situation Good choice
Windows-only admin task PowerShell (or batch for tiny legacy jobs)
Linux server, Docker image, CI job bash/sh
Team on mixed OSes, small automation PowerShell 7 or bash via Git Bash/WSL
Bigger tool, data processing, many OSes Python
You need it on every OS with zero installs two small scripts: .cmd + .sh (as in the mini project)

Learn more: Paths on Windows, macOS & Linux, PowerShell Files, Git Attributes.

Test yourself

A script fails on Linux with \r': command not found. What's wrong?

  1. bash is too old
  2. The file has Windows (CRLF) line endings
  3. It needs chmod +x
  4. It's UTF-16

Which separator does the PATH variable use on Windows?

  1. :
  2. ;
  3. /
  4. ,

Which PowerShell cmdlet builds a path with the right separator for the current OS?

  1. Split-Path
  2. Join-Path
  3. Resolve-Path
  4. Convert-Path