Linux bash bad interpreter no such file

Bash script – «/bin/bash^M: bad interpreter: No such file or directory» [duplicate]

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

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 :

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

I created the file in Windows using Notepad++, copied the file over to the server using WinSCP. And I know this isn’t the ideal way to do things

I got this with a hashbang misspelling: #! /user/bin/env python . note user instead of usr , so check your env top-line statement

I voted to reopen this question because the title contained /bin/bash^M: bad interpreter: No such file or directory , which led me from a Google search directly to a solution. The «duplicate» question did not.

11 Answers 11

The reason might be that you saved the file on Windows, with CR LF as the line ending ( \r\n ).

Run the following command in your terminal:

(Of course, change scriptname.sh to your file name)

The command will replace those CR characters with nothing, which will leave these lines with LF ( \n ) as the ending, and Bash will be able to read and execute the file.

If this not worked, try sed -i -e ‘s/^M$//’ scriptname.sh . (Press Ctrl+V Ctrl+M to insert that ^M .)

This didn’t work for me, including the . However, the original answer had a solution that did work for me: open the file in Vim and run the following command before saving: :set fileformat=unix listed under the SO question called Are shell scripts sensitive to encoding and line endings? did work for me.

bonus for working on docker containers that don’t have dos2unix installed. Though I couldn’t overwrite the script in my case so mine looked like cat scriptname.sh | sed -e ‘s/\r$//’ > fixedscriptname.sh

@Robert Molina, windows adds a carriage return character in addition to \n at the end of lines. This command simply removes it by substituting \r for an empty string using the linux stream edit command (sed).

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:

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.

Читайте также:  Xerox 6515 драйвер linux

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 Dos\Windows . To change it go to

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

Источник

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

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

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

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

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

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

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

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

sudo apt update && sudo apt install dos2unix
dos2unix script.sh dos2unix: converting file script.sh to Unix format. 

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

Источник

shell script: bad interpreter: No such file or directory when using pwd

faced the same issue. Created a new text file and renamed it to blah.sh.Edited it gvim to include #! /bin/sh and my commands.While runnin g on shell the «bad interpreter: No such file or directory» error was observed. Then deleted the file and created a similar file using vi editor in the shell and added the same set of line as in previous script and this time it worked without any fuss.

12 Answers 12

I had the same problem. Removing #!/bin/bash did the trick for me. It seems that is not necessary to add where bash is located, since it is on the system path.

I found another solution here. Change

This will lead to errors on other systems. For instance, your 2nd «shebang line» doesn’t work on Centos 6.

The echo: bad interpreter: No such file or directory is most likely coming from the first line, #. which is called shebang line.

About the #. line

This line hints the shell what interpreter to use to run the file. That can be e.g. bash , or sh (which is (roughly) a subset so a lot of things won’t work), or basically anything that can execute the file content — Perl, Python, Ruby, Groovy.

Читайте также:  Linux как посмотреть оборудование

The line points the system in cases like calling the script directly when it’s executable:

It is also often used by editors to recognize the right syntax highlighting when the file has no suffix — for instance, Gedit does that.

Solution

To override the line, feed the script to Bash as a parameter:

Or, you can ‘source’ it, which means, from within a Bash shell, do either of

source myScript.sh . myScript.sh 

which will work (roughly) as if you pasted the commands yourself.

Источник

Resolve Issue: Bin/Bash^M: Bad Interpreter: No Such File Or Directory

While working on different operating system platforms, we encountered a bundle of errors, i.e., performing some coding or installation. When we work in bash, we may encounter hundreds of bash related-errors. You could believe there is a permissions problem and attempt executing the chmod 777 instruction to give the bash script file all rights, but it will not solve the problem. It Is initiated by the carriage return “M”. The line feed symbol is used in Linux to indicate the finish of a line; meanwhile, the two-character combination CR LF is used in Windows. Your document has Windows line ends, which causes Linux to be perplexed. Let’s see the solutions for it.

In this tutorial, we will look at how to fix the problem that occurs while running bash or.sh file on a Linux environment. The poor interpreter is another name for this error. You might believe this is a permissions constraint and try using the chmod +x command to grant the shell script file all the required privileges, but this will not resolve the issue. The script specifies that it would be run using the “/bin/bash^M” shell. There is no such file; instead, “/bin/bash” is used. The “^M” character stands for carriage return.

The line feeding character is often used in Linux to indicate the ending of a line, whereas the two-character sequence CR/LF is often used in Windows-like operating systems. The file contains Windows line endings markers, which causes Linux to be perplexed. In a bash script file, how can I see CR or LF encoding characters? You may also view the line end characters as LFCR or LFCR by View → Show Symbol → Show End of Line. An example of a file with CR or LF characters is shown below:

The above and below displays are not available in the basic notepad editor; instead, you must install Notepad++, an advanced version of notepad. To fix the error in the Windows operating system, open the bash script file in the Notepad++ editor and then go to the preferences tab via the settings menu as below. Close the window after choosing Unix/OSX as the format. Afterwards, save and close the file.

Preferences → New Document/Default Directory Tab → Setting → Preferences → New Document/Default Directory Tab → Chose New Document Format →

Using Stream Editor Command

In UNIX, the SED command accounts for a line-by-line editor, and it can perform a wide range of file procedures such as scanning or searching, finding and replacing, inserting, and deleting. The SED command is most commonly used in UNIX and Linux-like operating systems for substituting or finding and replacing. Delete the CR characters that aren’t supposed to be there. You can use (sed) the command below in the image to accomplish this task:

Читайте также:  Пин код wps linux

By Using Dos2UNIX Utility

Dos2Unix is a Programme that converts DOS to UNIX. To resolve the shell script for the Unix-Linux like operating systems, install the dos2unix utility and then run the dos2unix command given below:

If you get the command not found error, first install the dos2unix utility by running the command below from a Linux command line shell:

You can use the unix2dos command to convert the file back to DOS format.

In a bash script file, how can I view CR LF characters? Attempt file, file -k, and finally dos2unix -ih command as in below screen: Attempt file, file -k, and finally dos2unix -ih command as in below screen. For the Linux/Unix line “CR,” it simply prints text.

You may install it on macOS operating system using Homebrew as follows:

Then do the execute the below command to convert the file in dos format to UNIX format:

What Is The Purpose Of The Command dos2unix

DOS2UNIX is a utility that translates DOS line endings CR (carriage return) +LF (line feed) to UNIX line encodings in text files LF (line feed). It can also convert between UTF-16 and UTF-8 characters. You can translate from UNIX to DOS while utilizing the unix2dos command. Expectantly, this will resolve the problem you were having.

By Using Vim Editor

If you don’t have the DOS2UNIX Utility installed on your LINUX operating system, you might use the VIM editor to transform your shell script’s format to UNIX. Use the succeeding instruction to open the file in VIM Editor:

vi FILENAME.sh

vim FILENAME.sh

If you’re not in the current directory or folder where your bash file script is located, type the directory’s full path, as I did. But if you are in the same directory or folder, you can run the command directly as given above. VIM is a progressive form of the VI editor. Both VI and VIM commands do the same work. Run the command underneath to change the file format to the UNIX operating system:

Then, using the commands below, all changes are saved and close the file in the editor, write the file, and close it. Now you’re done. You can convert the format of your shell script to UNIX through any of the approaches described previously. We hope the above information helped resolve your problem.

Conclusion

This is all about the use of simple methods to resolve the issue “bin/bash^M: bad interpreter: No such file or directory”. All the examples used here are simple and easy to implement. We hope that you like it and learn more from it.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.

Источник

Оцените статью
Adblock
detector