When working across multi-platform development teams where developers write code, shell scripts, or configuration files on Windows before deploying them to an Ubuntu server, unexpected runtime failures frequently occur. A shell script that executes cleanly on a local machine suddenly fails on Ubuntu with cryptic errors such as /bin/bash^M: bad interpreter: No such file or directory or causes Python scripts to throw syntax errors on seemingly empty lines.
This widespread issue is caused by a fundamental difference in how operating systems denote line breaks. Windows uses a two-character combination: Carriage Return followed by Line Feed (CRLF or \r\n). Linux and macOS, by contrast, use only a single Line Feed character (LF or \n). When Linux encounters the hidden ^M carriage return character, it treats it as literal command syntax. In this guide, you will learn how to diagnose, convert, and automate line ending conversions in Ubuntu using the dos2unix utility.
Why CRLF Line Endings Break Linux Scripts
Understanding line feed incompatibilities helps you troubleshoot deployment errors quickly:
- Breaks shebang interpreters: A shebang line written on Windows is read by Linux as
#!/bin/bash\r. Because no binary namedbash\rexists in/bin/, the kernel aborts execution immediately. - Corrupts configuration parsing: Nginx, Apache, Dockerfiles, and systemd units can fail to parse directives when hidden carriage returns append to variable values.
- Git merge conflicts: Committing mixed line endings inflates git diffs by marking every single line of a thousand-line file as modified.
Step 1: Installing dos2unix on Ubuntu
The dos2unix package is available directly from the standard Ubuntu repositories. Open your terminal and install it:
sudo apt update
sudo apt install dos2unix -y
Step 2: Checking File Line Endings Before Conversion
To inspect whether a file contains Windows CRLF carriage returns, use the file command:
file myscript.sh
If the file was created or edited on Windows, the output will explicitly declare:
myscript.sh: Bourne-Again shell script, ASCII text executable, with CRLF line terminators
Step 3: Converting Windows Files to Unix (LF)
To strip carriage returns and convert the file to native Unix line endings, pass the filename to dos2unix:
dos2unix myscript.sh
The tool converts the file in place and outputs: dos2unix: converting file myscript.sh to Unix format.... Run file myscript.sh again; the with CRLF line terminators warning will be gone, and the script will execute cleanly without interpreter errors.
Step 4: Batch Converting Entire Folders and Repositories
If you have cloned a project repository where dozens of files contain Windows line endings, convert all .sh scripts recursively:
find . -type f -name "*.sh" -exec dos2unix {} +
To convert all text files within a directory tree while preserving binary files:
find . -type f -exec dos2unix -q {} +