Resolving “/bin/bash^M: bad interpreter” with a Shellscript written on Windows in VS Code run on Linux

When writing Shellscripts on a Windows machine and then trying to use the scripts on Mac, I stumbled over the error below:

-bash: ./ /bin/bash^M: bad interpreter: No such file or directory

The problem here are the different line endings. Windows will mark the line ending with different control characters, maybe you saw them before, while adding a new line within a string. It is a ‘\n‘ on Unix like machines and ‘\r\n‘ on Windows.

Line endings in Windows, Linux and Mac

Like said before in Unix like systems the end of line (EOF) is marked by an ‘\n‘, called LF (line feed). In Windows a so called  CR (carriage return) and the LF is used.

When we write a script in an editor, which is set to CRLF and then try to execute this script on a linux or mac, the result would be the error from above.

To avoid this error you just have to write your script in an editor which supports LF.

How to change the line endings in Visual Studio Code

In Visual Studio Code it is very simple to change the line endings.

VS Code Win Line End Setting

In the left corner bottom of the editor you see a CRLF field. Click on it and then, on the top, a window will pop up.

VS Code Win LF

Now you can change the line ending from CRLF to LF. Next you have to save your file and you should be able to execute your script on your Unix like machine.

Other editors

You can find solutions for Sublime and Notepad++ in this post on StackOverflow.

You may also like...