Have you ever been slapped with the /bin/bash^M: bad interpreter: No such file or directory error when trying to run a bash script, be it from cron or command line?

This issue is caused when you create scripts in Windows environments and then port them over to run on a Unix environment : Unix uses different line endings therefore it can’t properly read the file you created on Windows. Bash scripts on the other hand are quite sensitive to line-endings. This is not just limited to the script itself. it extends to the data that the script processes.

With that in mind, it is important that one should have Unix-style line-endings, i.e., each line is terminated with a Line Feed character \n which is (decimal 10, hex 0A in ASCII).

With Windows or DOS-style line endings, each line is terminated with a Carriage Return followed by a Line Feed character \r\n.

The Bash script sees the Carriage Return \r as ^M. In this case, the Carriage Return (^M or \r) is not treated as whitespace. and is appended to the line as text wherever it appears at line endings. So this:

!/bin/bash   

becomes:

!/bin/bash^M

Since there is no interpreter, command, directory, or file called bash^M we get the bad interpreter: No such file or directory error.

How to fix it ?

Since we know ^M is an illegal character the simple solution is to get rid of it. We will just show you two simple ways to do it.

  • This can be done using the dos2unix program to convert the Carriage Return characters:
$ dos2unix filename

You can download the dos2unix program from this location.

  • Correct the problem from the source.

That is whichever editor (Sublime, Notepad++, VS Code, etc) you use in Windows you should be able to change the settings to use the Unix style line endings.

For example in Notepad++ in the bottom right of the screen, you will be able to see the document format. By default, it will say Windows (CR LF). To change it either:

  1. Go to Settings > Preferences
  2. Select New Document
  3. In the Format (Line ending) section select Unix (LF)
  4. Click the Close button to save preferences

or

  1. Right-click on the Windows (CR LF) label on the bottom right of the screen to trigger the context menu.
  2. Select Unix LF

PS: Each editor has their personalized ways of changing the Line ending format which should be shown in the bottom right corner of the editor window. Usually Left or right-clicking the label should display the options you have.

By Shabazz

Software Engineer, MCSD, Web developer & Angular specialist

Leave a Reply

Your email address will not be published. Required fields are marked *