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.
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.
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.shbash: 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$
hiThe 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.