Article explaining How to resolve /bin/bash^M: bad interpreter: No such file or directory in Unix or Linux server.
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 issue with files which 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 illegal character
^M in *nix systems. Hence you can see
^M in above error which is at end of very first line of script
#!/bin/bash which invokes bash shell in script.
To resolve this issue you need to convert DOS file into Linux one. You can either re-write whole file using text editors in Linux/Unix system or you can use tools like
dos2unix or native commands like
dos2unix utility which comes pre-installed in almost all distributions now a days.
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.
Syntax is pretty simple you need to give encoding format along with 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 file intact and dont mess around original file. If you are ok to directly edit 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 ...
-k keeps the time stamp of file intact and
-o converts file and overwrites changes to same file.
You can use stream line editor
sed to globally search an replace
root@kerneltalks # sed -i -e 's/\r$//' test_script.sh
-i uses source file, edit and overwrites to same file.
-e supplied following script code to be run on source file.
Thts it. You repaired your file from Windows to run fine on Linux system! Go ahead.. execute…!