Tag Archives: /bin/bash^M: bad interpreter: No such file or directory

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

 The article explaining How to resolve /bin/bash^M: bad interpreter: No such file or directory in Unix or Linux server.

How to resolve /bin/bash^M: bad interpreter: No such file or directory

Issue :

Sometimes we see below error while running scripts :

root@kerneltalks # ./test_script.sh
-bash: ./test_script.sh: /bin/bash^M: bad interpreter: No such file or directory

This is the issue with files that were created or updated in Windows and later copied over to Unix or Linux machine to execute. Since Windows (DOS) and Linux/Unix interpret line feeds and carriage returns differently. Window’s carriage returns interpreted as an illegal character ^M in *nix systems.  Hence you can see ^M in the above error which is at the end of a very first line of script #!/bin/bash which invokes bash shell in the script.

To resolve this issue you need to convert the DOS file into Linux one. You can either re-write the whole file using text editors in Linux/Unix system or you can use tools like dos2unix or native commands like sed.

Solution:

Use dos2unix utility which comes pre-installed on almost all distributions nowadays. dos2unix project hosted here.

There are different encoding you can choose to convert your file. -ascii is default conversion mode & it only converts line breaks. I used here -iso which worked fine for me.

The syntax is pretty simple you need to give encoding format along with the source and destination filenames.

root@kerneltalks # dos2unix -iso -n test_script.sh script_new.sh
dos2unix: active code page: 0
dos2unix: using code page 437.
dos2unix: converting file backup.sh to file script_new.sh in Unix format ...

This way you can keep old files intact and don’t mess with the original file. If you are ok to directly edit the old file then you can try below command :

root@kerneltalks # dos2unix -k -o test_script.sh
dos2unix: converting file test_script.sh to Unix format ...

Where -k keeps the timestamp of the file intact and -o converts the file and overwrites changes to the same file.

Or

You can use streamline editor sed to globally search an replace

root@kerneltalks # sed -i -e 's/\r$//' test_script.sh

where, -i uses source file, edit, and overwrites to the same file. -e supplied the following script code to be run on the source file.

That’s it. You repaired your file from Windows to run fine on the Linux system! Go ahead… execute…!