Strovent SystemsSign in
Reference

Script fails with "/bin/bash^M: bad interpreter" or "$'\r': command not found": Windows line endings

A script saved with Windows CRLF line endings fails on Linux with bad interpreter, required file not found or $'\r' errors. Find the CR characters, remove them.

You copy a shell script to a Linux host, make it executable, and it will not start. Depending on the shell you get one of these:

-bash: ./deploy.sh: /bin/bash^M: bad interpreter: No such file or directory
-bash: ./deploy.sh: cannot execute: required file not found
zsh: ./deploy.sh: bad interpreter: /bin/bash^M: no such file or directory

Or the script starts and then fails line by line:

deploy.sh: line 2: $'\r': command not found
deploy.sh: line 3: cd: $'/srv/app\r': No such file or directory

All of these mean the same thing: the file has Windows line endings.

Why it happens

Windows ends each line of a text file with two characters, carriage return and line feed (CR LF). Linux and other Unix systems end lines with LF only. When a file edited on Windows reaches a Linux host unchanged, every line still ends in a CR, shown as ^M or \r.

So the first line, #!/bin/bash, really names an interpreter called /bin/bash followed by a CR. No such program exists, and the kernel refuses to run the script. Bash 5.2 reports this as "cannot execute: required file not found"; Bash 5.1 and 5.3 name the interpreter with the ^M and say "bad interpreter".

If you run the script as bash deploy.sh, the first line is only a comment, so the script starts, but each command still ends in a CR: an empty line becomes the command $'\r', and a path gets a stray \r at the end.

Check for CR characters

file deploy.sh

prints ... with CRLF line terminators for such a file. cat -A deploy.sh shows each CR as ^M before the $ that marks the end of a line.

Remove them

With dos2unix, if it is installed:

dos2unix deploy.sh

Without it, GNU sed can strip a CR at the end of each line, editing the file in place:

sed -i 's/\r$//' deploy.sh

Then run the script again.

Stop it happening again

  • Save scripts with LF line endings in your editor on Windows. Most code editors show the line-ending style in the status bar and let you change it.
  • Do not count on the transfer to fix it. OpenSSH's sftp and scp have no text mode: between Windows, macOS and Linux they copy the file as it is, CRs included. Transfers to z/OS are different, because text is converted there: see IND$FILE, FTP or SFTP: which to use to move a file to or from z/OS.

Sources

Spotted a mistake? Email [email protected].