đ§ dos2unix: How to Fix Broken Shell Scripts
If youâve ever written a Bash script on Windows and then tried to run it on Linux, chances are youâve seen cryptic errors like:
-bash: ./script1.sh: cannot execute: required file not found
or
bash: ./script1.sh: /bin/bash^M: bad interpreter: No such file or directory
What happened? Windows sabotaged your scriptâor more precisely, you did. By default, Windows editors save files with CRLF (\r\n
) line endings, while Unix systems expect just LF (\n
). That invisible \r
(carriage return) completely wrecks interpreters, conditionals, and redirects.
Installing dos2unix
The easiest way to fix this is with the dos2unix
tool:
- Ubuntu / Debian:
sudo apt update
sudo apt install dos2unix
- Macos
brew install dos2unix
Check itâs installed:
dos2unix --version
Fixing Your Script
Once installed, just run:
dos2unix fuckedupscript.sh
This strips out all the \r
characters, and your script should run normally.
No dos2unix
? No Problem
If you canât install it, there are alternatives:
- sed
sed -i 's/\r$//' file.sh
- tr
tr -d '\r' < file.sh > fixed.sh && mv fixed.sh file.sh
Preventing the Mess
Best fix: avoid the problem altogether.
- Use an editor that can save files in Unix (LF) format.
- If you use Git, set these global configs to ensure CRLF is converted to LF on commit:
git config --global core.autocrlf input
git config --global core.eol lf
With this, your scripts wonât randomly break just because you switched systems.\
Epilog
CRLF vs LF is one of those tiny differences that cause big headaches. The good news is once you know the cause, the fix is simpleâand with the right Git or editor settings, youâll never have to âun-fuckâ a script again.