Меню

Ошибка bin bash m bad interpreter no such file or directory


Debian, Linux, Ubuntu

  • 17.03.2021
  • 11 489
  • 2
  • 16
  • 15
  • 1

Ошибка /bin/bashM: bad interpreter: No such file or directory при запуске скриптов

  • Содержание статьи
    • Вступление
    • Причина возникновения
    • Как исправить ошибку (способ 1: очень быстрый)
    • Как исправить ошибку (способ 2: медленный, но очень надежный)
    • Комментарии к статье ( 2 шт )
    • Добавить комментарий

Вступление

Иногда при запуске различных sh скриптов можно столкнуться вот с такой ошибкой:

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

В данной статье мы рассмотрим причину возникновения данной ошибки и о способах ее исправления.

Причина возникновения

Как видно из текста ошибки, при запуске скрипта вместо стандартного шелла /bin/bash скрипт пытается запустить его из директории /bin/bash^M и ожидаемо выдает ошибку, потому что такого пути не существует. Все дело в том, что ^M — это символ возврата каретки (окончания строки), который обычно используется на Windows системах. По всей видимости, данный скрипт редактировался каким-либо текстовым редактором, в настройках которого был выставлен режим Windows (а не Linux) и из-за этого, при запуске скрипта получается такая ошибка.

Как исправить ошибку (способ 1: очень быстрый)

Допустим, наш скрипт, при запуске которого мы получаем ошибку будет называться script.sh.
1) Делаем его резервную копию, чтобы иметь возможность восстановить работоспособность, если что-либо пойдет не так.
2) Запускаем следующую команду:

sed -i -e 's/r$//' script.sh

Она должна заменить все символы переноса строки Windows на те, которые используются на Linux системах. Способ не совсем универсальный, поэтому иногда может не сработать.
3) После выполнения данной команды, пытаемся запустить на скрипт script.sh и проверить работоспособность. Если не помогло, то восстанавливаем оригинал из резервной копии и переходим ко второму способу.

Как исправить ошибку (способ 2: медленный, но очень надежный)

Если первый способ не помог, либо если вы часто сталкиваетесь с такой ошибкой, то можно воспользоваться специальной утилитой dos2unix, которая как раз подходит для таких случаев
1) Делаем резервную копию script.sh, чтобы восстановить его в случае проблем.
2) Устанавливаем утилиту dos2unix

sudo apt update && sudo apt install dos2unix

3) Выполняем команду:

dos2unix script.sh 
dos2unix: converting file script.sh to Unix format...

4) После выполнения данной команды, пытаемся запустить на скрипт script.sh и проверить работоспособность.

I’m using this tutorial to learn bash scripts to automate a few
tasks for me.
I’m connecting to a server using putty.

The script, located in .../Documents/LOG, is:

#!/bin/bash
# My first script
echo "Hello World!"

And I executed the following for read/write/execute permissions

chmod 755 my_script

Then, when I enter ./my_script, I’m getting the error given in the
title.

Some similar questions wanted to see these, so I think they might
help :

$ which bash
/bin/bash

and

$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/bin/mh

I tried adding the current directory to PATH, but that doesn’t
work …

Henke's user avatar

Henke

3,6713 gold badges25 silver badges36 bronze badges

asked Jan 8, 2013 at 16:03

cartonn's user avatar

7

Run following command in terminal

sed -i -e 's/r$//' scriptname.sh

Then try

./scriptname.sh

It should work.

answered Apr 20, 2015 at 12:13

Nivin V Joseph's user avatar

Nivin V JosephNivin V Joseph

10.8k2 gold badges15 silver badges24 bronze badges

7

I have seen this issue when creating scripts in Windows env and then porting over to run on a Unix environment.

Try running dos2unix on the script:

http://dos2unix.sourceforge.net/

Or just rewrite the script in your Unix env using vi and test.

Unix uses different line endings so can’t read the file you created on Windows. Hence it is seeing ^M as an illegal character.

If you want to write a file on Windows and then port over, make sure your editor is set to create files in UNIX format.

In notepad++ in the bottom right of the screen, it tells you the document format. By default, it will say DosWindows. To change it go to

  • settings->preferences
  • new document / default directory tab
  • select the format as unix and close
  • create a new document

answered Jan 8, 2013 at 16:07

cowls's user avatar

cowlscowls

23.6k8 gold badges48 silver badges78 bronze badges

16

If you use Sublime Text on Windows or Mac to edit your scripts:

Click on View > Line Endings > Unix and save the file again.

enter image description here

fivestones's user avatar

answered Apr 21, 2014 at 17:26

Mario Campa's user avatar

Mario CampaMario Campa

4,0121 gold badge24 silver badges25 bronze badges

6

In notepad++ you can set it for the file specifically by pressing

Edit —> EOL Conversion —> UNIX/OSX Format

enter image description here

answered Jun 3, 2014 at 10:54

Urik's user avatar

UrikUrik

1,5183 gold badges19 silver badges36 bronze badges

3

This is caused by editing file in windows and importing and executing in unix.

dos2unix -k -o filename should do the trick.

answered Aug 13, 2013 at 11:17

StonecoldIM's user avatar

StonecoldIMStonecoldIM

6541 gold badge6 silver badges6 bronze badges

2

problem is with dos line ending. Following will convert it for unix

dos2unix file_name

NB: you may need to install dos2unix first with yum install dos2unix

another way to do it is using sed command to search and replace the dos line ending characters to unix format:

$sed -i -e 's/r$//' your_script.sh

answered Aug 31, 2016 at 11:10

Md. Shafiqur Rahman's user avatar

Your file has Windows line endings, which is confusing Linux.

Remove the spurious CR characters. You can do it with the following command:

 $ sed -i -e 's/r$//' setup.sh

answered May 19, 2016 at 10:16

kalyani chaudhari's user avatar

1

For Eclipse users, you can either change the file encoding directly from the menu File > Convert Line Delimiters To > Unix (LF, n, 0Α, ¶):

Eclipse change file encoding

Or change the New text file line delimiter to Other: Unix on Window > Preferences > General > Workspace panel:

Eclipse workspace settings

answered May 1, 2017 at 9:21

Christos Lytras's user avatar

Christos LytrasChristos Lytras

35.4k4 gold badges76 silver badges107 bronze badges

2

I was able to resolve the issue by opening the script in gedit and saving it with the proper Line Ending option:

File > Save As…

In the bottom left of the Save As prompt, there are drop-down menus for Character Encoding and Line Ending. Change the Line Ending from Windows to Unix/Linux then Save.

Selecting the "Line Ending" option as "Linux/Unix" in the gedit "Save As" prompt

answered May 26, 2016 at 19:10

NWRichmond's user avatar

NWRichmondNWRichmond

3013 silver badges6 bronze badges

1

I develop on Windows and Mac/Linux at the same time and I avoid this ^M-error by simply running my scripts as I do in Windows:

$ php ./my_script

No need to change line endings.

answered Nov 4, 2016 at 17:32

MrMacvos's user avatar

MrMacvosMrMacvos

1032 silver badges8 bronze badges

I wanted to execute a shell script:

-rwxr-x--x 1 root root   17234 Jun  6 18:31 create_mgw_3shelf_6xIPNI1P.sh

I tried to do a standard procedure, but I got this error:

./create_mgw_3shelf_6xIPNI1P.sh 
localhost 389 -l /opt/fews/sessions/AMGWM19/log/2013-06-06-143637_CLA-0 
DEBUG   cd/etc/opt/ldapfiles/ldif_in ;
./create_mgw_3shelf_6xIPNI1P.sh 
localhost 389 -l /opt/fews/sessions/AMGWM19/log/2013-06-06-143637_CLA-0
**ERROR  sh: ./create_mgw_3shelf_6xIPNI1P.sh: /bin/bash^M: bad interpreter: No such file or directory**

What does it mean? I was doing this as the root user under the root group.

Does it mean that the file does not have the correct permission for the root user?

edwinksl's user avatar

edwinksl

23.3k16 gold badges73 silver badges100 bronze badges

asked Jun 6, 2013 at 20:17

user165062's user avatar

This isn’t a permission issue, you aren’t getting a message about permissions

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

The script indicates that it must be executed by a shell located at /bin/bash^M. There is no such file: it’s called /bin/bash.

The ^M is a carriage return character. Linux uses the line feed character to mark the end of a line, whereas Windows uses the two-character sequence CR LF. Your file has Windows line endings, which is confusing Linux.

Remove the spurious CR characters. You can do it with the following command:

sed -i -e 's/r$//' create_mgw_3shelf_6xIPNI1P.sh

answered Jun 6, 2013 at 20:25

Gilles 'SO- stop being evil''s user avatar

11

In vim you could also use :set ff=unix and then save the file, or :set ff=dos to get DOS formatting again.

answered Jun 7, 2013 at 8:33

ortang's user avatar

ortangortang

2,05314 silver badges13 bronze badges

1

Your file has DOS/Windows style line endings (CR LF), but on Unix-like systems only the LF control character is used as line break.

The additional CR control character is shown encoded as ^M in your output. You can also see it when you run cat -A create_mgw_3shelf_6xIPNI1P.sh.

To convert the line endings from DOS/Windows style to Unix style, there’s a tool called dos2unix. You install it using:

sudo apt-get install dos2unix

Then you can simply convert files’ line endings in both ways using

dos2unix FILENAME
unix2dos FILENAME

In your case, simply run this command below and the script file will be converted in-place:

dos2unix create_mgw_3shelf_6xIPNI1P.sh

After that Bash should be able to interpret the file correctly.

answered Dec 15, 2016 at 20:31

Byte Commander's user avatar

Byte CommanderByte Commander

103k43 gold badges277 silver badges418 bronze badges

1

The Problem ist you edit with Dos!

open your file with vi
then set unix with:

:set ff=unix
:wq

and it all fine

muru's user avatar

muru

188k50 gold badges459 silver badges709 bronze badges

answered Apr 28, 2016 at 16:29

DaFreder's user avatar

DaFrederDaFreder

1511 silver badge2 bronze badges

Do vi <your script>.

then :set list; it will display any of the special characters in your script.

then replace the character:

:%s/^M//gc [to type ^M press Ctrl + v + m]

strugee's user avatar

strugee

1,0921 gold badge10 silver badges25 bronze badges

answered Jun 7, 2013 at 7:41

Pankaj Sain's user avatar

2

As explained in the other answers, this is a format issue. So, the answer is to change the format from DOS to Unix style line endings. This is yet another simple way to fix your file ‘in place’

fromdos file

It’s available in package tofrodos:

sudo apt-get install tofrodos

Byte Commander's user avatar

answered Jun 7, 2013 at 22:50

josediazaz's user avatar

You can also use gedit to remove the unwanted characters.
Under the File menu select Save As and set the line end type unix/Linux.

Seth's user avatar

Seth

56.1k43 gold badges143 silver badges196 bronze badges

answered Dec 3, 2013 at 2:40

tphistry's user avatar

1

I had developed the bash script on a Mac, so the first line of the script was

#!/opt/homebrew/bin/bash

When I tried to run it on ubuntu, I got the bad-interpreter issue. I changed the first line to

/usr/bin/bash

This change worked on ubuntu which bash command on ubuntu to find the path of bash.

answered Aug 26, 2022 at 11:59

Siddharth's user avatar

SiddharthSiddharth

3311 gold badge4 silver badges28 bronze badges

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?

If your answer is yes then you have reached the right place. This error is more common than you think and is quite harmless but nevertheless, it is annoying.

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 rn.

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.

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

There are several options one may have to solve this problem. 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.

1. 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.

2. 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:

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

or

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

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.

Conclusion

There you have it. You should be able to understand why and get rid of the /bin/bash^M: bad interpreter: No such file or directory bash script error from all your scripts and data they act upon.

Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.

This kind of message is usually due to a bogus shebang line, either an extra carriage return at the end of the first line or a BOM at the beginning of it.

Run:

$ head -1 yourscript | od -c

and see how it ends.

This is wrong:

0000000   #   !   /   b   i   n   /   b   a   s   h  r  n

This is wrong too:

0000000 357 273 277   #   !   /   b   i   n   /   b   a   s   h  n

This is correct:

0000000   #   !   /   b   i   n   /   b   a   s   h  n

Use dos2unix (or sed, tr, awk, perl, python…) to fix your script if this is the issue.

Here is one that will remove both of a BOM and tailing CRs:

sed -i '1s/^.*#//;s/r$//' brokenScript

Note that the shell you are using to run the script will slightly affect the error messages that are displayed.

Here are three scripts just showing their name (echo $0) and having the following respective shebang lines:

correctScript:

0000000   #   !   /   b   i   n   /   b   a   s   h  n

scriptWithBom:

0000000 357 273 277   #   !   /   b   i   n   /   b   a   s   h  n

scriptWithCRLF:

0000000   #   !   /   b   i   n   /   b   a   s   h  r  n

Under bash, running them will show these messages:

$ ./correctScript
./correctScript
$ ./scriptWithCRLF
bash: ./scriptWithCRLF: /bin/bash^M: bad interpreter: No such file or directory
$ ./scriptWithBom
./scriptWithBom: line 1: #!/bin/bash: No such file or directory
./scriptWithBom

Running the bogus ones by explicitely calling the interpreter allows the CRLF script to run without any issue:

$ bash ./scriptWithCRLF
./scriptWithCRLF
$ bash ./scriptWithBom
./scriptWithBom: line 1: #!/bin/bash: No such file or directory
./scriptWithBom

Here is the behavior observed under ksh:

$ ./scriptWithCRLF
ksh: ./scriptWithCRLF: not found [No such file or directory]
$ ./scriptWithBom
./scriptWithBom[1]: #!/bin/bash: not found [No such file or directory]
./scriptWithBom

and under dash:

$ ./scriptWithCRLF
dash: 2: ./scriptWithCRLF: not found
$ ./scriptWithBom
./scriptWithBom: 1: ./scriptWithBom: #!/bin/bash: not found
./scriptWithBom

If you are trying to run a shell script and getting the following error,

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

You may think that this is a permission issue and might try running the chmod 777 command to provide all the permissions to the shell script file, but that will not fix the issue.

The script indicates that it must be executed by a shell located at /bin/bash^M. There is no such file, it’s called /bin/bash.

The ^M is a carriage return character. Linux uses the line feed character to mark the end of a line, whereas Windows uses the two-character sequence CR LF. Your file has Windows line endings, which is confusing Linux.

Using sed Command

Remove the spurious CR characters. You can do it with the following command:

sed -i -e 's/r$//' NAME-OF-FILE.sh

Using dos2unix Program

Or, you can install the dos2unix program and then run the dosrunix command to fix the shell script as per unix operating system.

dos2unix NAME-OF-FILE.sh

To install dos2unix utility in your UNIX system, run the following command:

sudo apt-get install dos2unix

To convert the file back to DOS formatting, you cna use the unix2dos command.


Using vim Editor

If you do not have the dos2unix utility installed, you can use the Vim editor to convert the formatting of your shell script to unix. Open the file in the vim editor.

vi NAME-OF-FILE.sh

Run the following command,

:set ff=unix

Then write the file and close it using the following command:

:wq!

And you are done.

You can use any of the above mentioned techniques to change the formatting of your shell script to UNIX. We hope this article helped you with your issue.

You may also like:

  • Unix vs Linux: Comparison Between Unix and Linux
  • What is Vi Editor in Linux?
  • Ifconfig Command in Linux
  • Learn Basic Vim Commands

 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…!

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка bf4 отсутствует msvcp120 dll
  • Ошибка bigup2 dll что делать