Fix CRLF Line Endings & Quoting Bugs in Bash
Why Windows CRLF line endings break shebangs with 'bad interpreter' and how unquoted Bash variables split filenames with spaces.
You'll learn why /bin/bash^M: bad interpreter happens when scripts have Windows line endings, how unquoted $var expansions break on spaces or globs, and how set -euo pipefail + shellcheck catch shell bugs early.
1. The big idea
Two invisible characters cause half of all "mysterious" Bash failures: carriage returns (\r, shown as ^M) from Windows editors, and unquoted spaces in $VARIABLE expansions. Bash treats \r as part of the command name or interpreter path, and splits unquoted variables on whitespace.
2. Detecting and stripping CRLF (\r\n) line endings
If a script fails with /usr/bin/env: 'bash\r': No such file or directory or syntax error near unexpected token $'\r', the file uses CRLF instead of Unix LF.
# Check line endings visually
file deploy.sh
# Output if broken: "Bourne-Again shell script, ASCII text executable, with CRLF line terminators"
# Convert CRLF to LF cleanly
dos2unix deploy.sh
# Or without extra packages installed:
sed -i 's/\r$//' deploy.shPrevent Git from reintroducing CRLF on shell scripts by adding a .gitattributes file to your repo:
*.sh text eol=lf3. Quoting variables and hardening scripts
In Bash, always double-quote variable expansions ("$var"). Without quotes, a filename like My Report.pdf splits into two arguments (My and Report.pdf), and * expands into every file in the directory.
#!/usr/bin/env bash
set -euo pipefail
target_dir="${1:-}"
if [[ -z "$target_dir" ]]; then
echo "Usage: $0 <target-dir>" >&2
exit 1
fi
# Safe: quoted "$file" preserves spaces and special characters
for file in "$target_dir"/*.log; do
[[ -e "$file" ]] || continue
echo "Archiving: $file"
doneVerify your shell scripts use Unix LF endings (file script.sh), start with set -euo pipefail, double-quote every "$var", and pass shellcheck with zero warnings.
4. Common pitfalls
| Mistake | Why it fails | Better fix |
|---|---|---|
Editing .sh files with CRLF | Kernel looks for /bin/bash\r and fails immediately | Run dos2unix and enforce eol=lf in .gitattributes |
Writing rm -rf $DIR/* unquoted | Word-splits spaces; if $DIR is empty, runs rm -rf /* | Always quote "$DIR" and enable set -u |
Parsing ls output in a for loop | Breaks on filenames with spaces or newlines | Glob directly with for f in "$dir"/*; do |
Using single [ instead of [[ | Unquoted empty variables cause syntax errors | Use Bash [[ ... ]] for conditionals |
5. What you learned
You now know how to spot and fix CRLF interpreter errors, enforce LF line endings with .gitattributes, and write safer Bash scripts with set -euo pipefail, proper double-quoting, and shellcheck.