Skip to content
shellhacks.dev
Shell Scripting

Detect Windows Line Endings in a Shell Script

Find Windows line endings in a script with file script.sh and cat -A. The shebang ends in a carriage return, so the shell cannot find the interpreter.

2 min read
Summarize in AI

A script copied from a Windows machine fails with an error that mentions a path with a strange character, or with "command not found" on the first line.

Shell
printf '#!/bin/bash\r\necho hi\r\n' > s.sh && chmod +x s.sh
./s.sh
file s.sh
head -n 1 s.sh | cat -A
sed -i 's/\r$//' s.sh
./s.sh
Text
bash: line 2: ./s.sh: cannot execute: required file not found
s.sh: Bourne-Again shell script, ASCII text executable, with CRLF line terminators
#!/bin/bash^M$
hi

The first line is read by the kernel, which takes everything up to the newline as the interpreter path, carriage return included, so it looks for a program named /bin/bash followed by ^M, which does not exist. Bash 5.2 reports that the required file was not found, and older shells say bad interpreter. file recognizes the line terminators, and cat -A shows each end of line as ^M$. Removing the carriage return at the end of every line fixes it, as the last run shows. The shebang rule is in execve(2).

If the script is run as bash s.sh, the shebang is not used and the symptom changes: errors appear on later lines, as "command not found" for a line that looks fine, with a carriage return shown in the message. Tell Git not to convert line endings behind your back with a .gitattributes rule such as *.sh text eol=lf. The sed -i form as written is GNU syntax.

Share

More snippets

Shell Scripting

Return Text from a Function in POSIX sh

A POSIX sh function returns text by printing it, and the caller captures the output with command substitution. Variables set inside are lost, and trailing newlines go.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.