Chapter 15: Cross-Platform Strategies
Modern development rarely happens in a vacuum. You might develop on Windows but deploy to Linux, or use a Mac while managing Windows servers. This chapter covers the tools and strategies for writing scripts that bridge these ecosystems.
I. WSL: The Linux Engine on Windows
WSL (Windows Subsystem for Linux) has evolved from a translation layer (WSL1) to a full lightweight virtual machine running a genuine Linux kernel (WSL2).
WSL1 vs. WSL2
| Feature | WSL1 | WSL2 |
|---|---|---|
| Linux Kernel | Emulated (Syscall Translation) | Genuine Linux Kernel |
| File System Perf | Fast (on Windows drive) | Ultra-Fast (on Linux drive) |
| Compatibility | Partial | Full (Docker, FUSE, etc.) |
| Architecture | Direct on Windows | Managed Hypervisor |
II. The Power of Interop
One of the most unique features of WSL is the ability to mix Windows and Linux commands in a single pipeline.
1. Running Windows Tools from Linux
You can call .exe files from within Bash. WSL handles the path translation and execution.
# Search for text in a Windows directory using Linux grep
ls /mnt/c/Users/Jane/Documents | grep "Project"
# Open the current Linux directory in Windows Explorer
explorer.exe .
2. Running Linux Tools from CMD/PowerShell
# Get the first 5 lines of a file using Linux head from PowerShell
wsl head -n 5 data.txt
III. Path Translation: wslpath
Windows and Linux use different path formats.
- Windows:
C:\Users\Jane - Linux:
/mnt/c/Users/Jane
The wslpath tool is essential for scripts that need to pass file paths between the two environments.
# Convert Windows path to Linux path
LINUX_PATH=$(wslpath "C:\Users\Jane\config.ini")
IV. Handling Cross-Platform Line Endings
As discussed in the previous chapter, CRLF vs LF is the most common cause of script failure.
- Pro-Tip: Configure Git to handle this automatically by setting
core.autocrlftoinput(for Linux/Mac) ortrue(for Windows). - Manual Fix: Use the
dos2unixtool to convert files.dos2unix my_script.sh
V. Universal Logic: The "If-Os" Pattern
If you are writing a script that must run on both Mac and Linux, you can detect the OS and adjust flags accordingly (e.g., sed flags are different on macOS).
OS_TYPE=$(uname)
if [[ "$OS_TYPE" == "Darwin" ]]; then
# macOS Specific Logic
sed -i '' 's/old/new/g' file.txt
elif [[ "$OS_TYPE" == "Linux" ]]; then
# Linux Specific Logic
sed -i 's/old/new/g' file.txt
fi
In the final chapter, we'll wrap up with Security and Best Practices to ensure your production scripts are safe and maintainable.