No such file or directory ubuntu как исправить

I’ve downloaded a game (Shank) but the bin file doesn’t run. The error that is shown when I try to launch the executable is:

bash: ./shank-linux-120720110-1-bin: No such file or directory

asked May 7, 2012 at 19:06

Francesco's user avatar

FrancescoFrancesco

2,8812 gold badges14 silver badges12 bronze badges

7

You’re probably trying to run a 32-bit binary on a 64-bit system that doesn’t have 32-bit support installed.

There are three cases where you can get the message “No such file or directory”:

  • The file doesn’t exist. I presume you’ve checked that the file does exist (perhaps because the shell completes it).
  • There is a file by that name, but it’s a dangling symbolic link.
  • The file exists, and you can even read it (for example, the command file shank-linux-120720110-1-bin displays something like “ELF 32-bit LSB executable …”), and yet when you try to execute it you’re told that the file doesn’t exist.

The error message in this last case is admittedly confusing. What it’s telling you is that a key component of the runtime environment necessary to run the program is missing. Unfortunately, the channel through which the error is reported only has room for the error code and not for this extra information that it’s really the runtime environment that’s to blame. If you want the technical version of this explanation, read Getting “Not found” message when running a 32-bit binary on a 64-bit system.

The file command will tell you just what this binary is. With a few exceptions, you can only run a binary for the processor architecture that your release of Ubuntu is for. The main exception is that you can run 32-bit (x86, a.k.a. IA32) binaries on 64-bit (amd64, a.k.a. x86_64) systems.

In Ubuntu up to 11.04, to run a 32-bit binary on a 64-bit installation, you need to install the ia32-libs package Install ia32-libs. You may need to install additional libraries (you’ll get an explicit error message if you do).

Since 11.10 (oneiric) introduced multiarch support, you can still install ia32-libs, but you can choose a finer-grained approach, it’s enough to get libc6-i386 Install libc6-i386 (plus any other necessary library).

Community's user avatar

answered May 7, 2012 at 21:47

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

9

64 bit Ubuntu Multiarch systems

Follow this answer only if the output of file file-name shows,

file-name: ELF 32-bit LSB  executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.8, not stripped

To run 32bit executable file in a 64 bit multi-arch Ubuntu system, you have to add i386 architecture and also you have to install libc6:i386,libncurses5:i386,libstdc++6:i386 these three library packages.

sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386
./file-name

Community's user avatar

answered Apr 24, 2014 at 13:14

Avinash Raj's user avatar

Avinash RajAvinash Raj

76.6k55 gold badges213 silver badges252 bronze badges

4

To expand on @Gilles answer, there are at least three scenarios resulting in this error:

  1. The file doesn’t exist.
  2. The file exists but is a dangling symbolic link.
  3. The file exists (e.g. file command works), making for a puzzling error message. This may mean there’s a problem with the loader.

Categories of loader problems:

  1. An executable’s loader does not exist. You can check this using the file command and see if the loader does exist. E.g.

    file lmgrd
    lmgrd: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-lsb-x86-64.so.3, for GNU/Linux 2.6.18, stripped
    

    Notice interpreter /lib64/ld-lsb-x86-64.so.3; if this file does not exist, you need to install it. For this particular loader on 16.04, the answer turned out to be sudo apt-get install lsb.

  2. Issues with a script’s loader (see this answer).

  3. Missing shared libraries — use ldd <file-name> to check for any “not found” libraries. See this answer for more info.

The loader not existing could be due to a 32/64 bit mismatch or some other reason. There might be other kinds of loader errors I don’t know about.

answered May 11, 2018 at 18:54

jtpereyda's user avatar

jtpereydajtpereyda

2,0253 gold badges20 silver badges21 bronze badges

4

Here’s a transcript showing a bit more about the nature of the problem, and how to fix it as of Ubuntu 16.04. Notice that even though file reports “dynamically linked”, ldd reports “not a dynamic executable”.

$ ./myprogram
bash: myprogram: No such file or directory

$ file myprogram
myprogram: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.2.5, not stripped

$ ldd myprogram
    not a dynamic executable

Once you install libc6:i386, things start improving…

$ sudo apt-get install libc6:i386 # the initial fix
...

$ ldd myprogram
    linux-gate.so.1 =>  (0xf77fd000)
    libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xf7626000)
    /lib/ld-linux.so.2 (0x56578000)

$ ./myprogram
myprogram: error while loading shared libraries: libstdc++.so.6: cannot open shared object file: No such file or directory

To complete the job, you may need to identify and install additional libraries one at a time…

$ sudo apt-get install libstdc++6:i386 ## may require various additional libs

$ ./myprogram
... works correctly ...

I don’t know if there is a systematic way of identifying the correct libraries to install. There is a bit of guesswork mapping the error messages to package names (tab completion helps).

answered Jun 8, 2016 at 20:57

Brent Bradburn's user avatar

Brent BradburnBrent Bradburn

2,7362 gold badges29 silver badges35 bronze badges

1

By installing the deb for 32 bit I realized I was missing some libraries (in addition to ia32-libs and libc6). I first solved this problem by giving this command:

sudo apt-get install -f          

Then I got another error:

Message: SDL_GL_LoadLibrary 
Error: Failed loading libGL.so.1

Obviously, these libraries were properly installed. Without going into details I had to link the libraries by hand. I realized then that could also an easier solution through Synaptic install the following packages:

libgl1-mesa-glx:i386
libgl1-mesa-dri: i386.

After that the next problem was the black screen while playing, which I solved by replacing the executable in /Shank/bin with this:
http://treefort.icculus.org/smb/smb-linux-mesa-hotfix-test.tar.bz2.

I hope it will be useful to someone.
If you need more help or more details please feel free to contact me.

kiri's user avatar

kiri

27.4k16 gold badges80 silver badges117 bronze badges

answered May 9, 2012 at 19:12

Francesco's user avatar

FrancescoFrancesco

2,8812 gold badges14 silver badges12 bronze badges

This error happens when working on Windows (which introduces extra characters because of different line separator than Linux system) and trying to run this script (with extra characters inserted) in Linux. The error message is misleading.

In Windows, the line separator is CRLF (rn) whereas in linux it is LF (n). In my case, this happened due to working on Windows and uploading to Unix server for execution.

answered Jan 24, 2020 at 2:55

PALEN's user avatar

PALENPALEN

1,0811 gold badge8 silver badges6 bronze badges

2

Google navigated me to this page. My issue was distantly related to the title of this thread, so I am posting it here for the future visitors like me:

It is one of the weirdest issues:

$ ls -lh
ls: cannot access .~dataprep.ipynb: No such file or directory
-????????? ? ?      ?           ?            ? .~dataprep.ipynb
-rw------- 1 tgowda mygroup 475K Jun 12 15:59 dataprep.ipynb

I see that the file .~dataprep.ipynb is right there with some weird ?? permissions.
I just wanted to get rid of that messed up file.
rm command could not remove it. mv command couldn’t move it.

And then…

$ python
>>> from pathlib import Path
>>> list(Path('.').glob("*.ipynb"))
[PosixPath('.~dataprep.ipynb'), PosixPath('dataprep.ipynb')]
>>> p = list(Path('.').glob("*.ipynb"))[0]
>>> p
PosixPath('.~dataprep.ipynb')
>>> p.unlink()
>>> list(Path('.').glob("*.ipynb"))
[PosixPath('dataprep.ipynb')]

And that’s how I was able to defeat it.

answered Jun 13, 2020 at 3:36

Thamme Gowda's user avatar

None of the above answers worked for me because there was a miss-resolving for the interpreter.

I have written a detailed answer here, explaining how to fix this issue.

Thanks to this man who shared his experience with others solution here.
thanks to him i was able to solve this problem.

To summarize, as @steeldriver though, there was an interpreter problem.
the linker is giving to my program [/lib/ld64.so.1] as ELF interpreter but this path doesnt exist at all and i checked it by:

> ls /lib/ld64.so.1
ls: cannot access '/lib/ld64.so.1': No such file or directory

After that, i checked the interpreters path’s on my ubuntu installation by:

> ls /lib64/ld-*
/lib64/ld-linux-x86-64.so.2  /lib64/ld-lsb-x86-64.so.2  /lib64/ld-lsb-x86-64.so.3

so the solution is to create a link of one of this interpreters to the inexistant interpreter path by:

sudo ln -s /lib64/ld-linux-x86-64.so.2 /lib/ld64.so.1

Now we re-check the inexistent interpreter one more time to see if its still inexisting or not:

> ls /lib/ld64.so.1
/lib/ld64.so.1

Now this command has returned /lib/ld64.so.1 instead of “inexistant file”. so the problem was solved and i could run ./main successfully

So, in a summary, you have to create a link of one of this interpreters to the inexistant interpreter path by running the following command in a terminal (Ctrl + Alt + T) :

sudo ln -s /lib64/ld-linux-x86-64.so.2 /lib/ld64.so.1

answered Jan 28, 2022 at 21:06

Mohamed Elleuch's user avatar

3

Каждый пользователь, рано или поздно сталкивается с определенными проблемами в своей операционной системе Linux. Это может быть просто неправильное использование команд или их непонимание, так и такие серьезные ошибки Linux, как отсутствие драйверов, неработоспособность сервисов зависание системы и так далее.

Эта статья ориентирована в первую очередь на новичков, которые не знают, что делать когда их будут поджидать проблемы linux, мы дадим общую концепцию и попытаемся показать в какую сторону двигаться дальше. Мы рассмотрим исправление ошибок в linux как простых, так и более сложных. Но давайте сначала определим, какие проблемы linux будем рассматривать, разобьем их на категории:

  • Проблемы с командами в терминале
  • Проблемы с программами
  • Проблемы с драйверами и ядром
  • Проблемы с графической оболочкой
  • Проблемы с диском и файловой системой

Все это мы рассмотрим ниже, но сначала общее введение и немного теории.

Linux очень сильно отличается от WIndows, это заметно также при возникновении проблем Linux. Вот допустим, произошла ошибка в программе Windows, она полностью закрывается или выдает непонятное число с кодом ошибки и все, вы можете только догадываться или использовать поиск Google, чтобы понять что произошло. Но в Linux все совсем по-другому. Здесь каждая программа создает лог файлы, в которых мы можем при достаточном знании английского или даже без него, выяснить, что произошло. Более того, если программу запускать из терминала, то все ошибки linux и предупреждения мы увидим прямо в окне терминала. и сразу можно понять что нужно делать.

Причем вы сможете понять что произошло, даже не зная английского. Главным признаком ошибки есть слово ERROR (ошибка) или WARNING (предупреждение). Рассмотрим самые частые сообщения об ошибках:

  • Permission Denied – нет доступа, означает что у программы нет полномочий доступа к определенному файлу или ресурсу.
  • File or Directory does not exist – файл или каталог не существует
  • No such file or Directory – нет такого файла или каталога
  • Not Found – Не найдено, файл или ресурс не обнаружен
  • Connection Refused – соединение сброшено, значит, что сервис к которому мы должны подключиться не запущен
  • is empty – означает, что папка или нужный файл пуст
  • Syntax Error – ошибка синтаксиса, обычно значит, что в конфигурационном файле или введенной команде допущена ошибка.
  • Fail to load – ошибка загрузки, означает что система не может загрузить определенный ресурс, модуль или библиотеку (fail to load library) обычно также система сообщает почему она не может загрузить, permission denied или no such file и т д.

Сообщения об ошибках, кроме терминала, мы можем найти в различных лог файлах, все они находятся в папке /var/log, мы рассматривали за какие программы отвечают определенные файлы в статье просмотр логов linux. Теперь же мы подробнее рассмотрим где и что искать если linux выдает ошибку.

Проблемы с командами в терминале

Обычно проблемы с командами в терминале возникают не из-за ошибки linux или потому, что разработчики что-то недоработали, а потому, что вы ввели что-то неправильно или предали не те что нужно опции.

Если были переданы не те опции, то, скорее всего, программа покажет вам справку, ознакомившись с которой вы сможете очень быстро понять в чем проблема. Также справку выдают множество команд если их запустить без параметров.

Также довольно частой ошибкой при выполнении команд есть неиспользование команды sudo перед самой командой для предоставления ей прав суперпользователя. В таких случаях вы обычно получаете ошибку Permission Denied или просто уведомление, что не удалось открыть тот или иной файл или ресурс: can not open …, can not read … и так далее.

Если файла, которого вы передали в параметрах не существует, то вам будет об этом сказано соответствующим сообщением. Сообщения могут быть и более специфичные, в зависимости от ошибки, но в конце концов, вы можете воспользоваться переводчиком Google, чтобы понять смысл того, что хочет система.

Очень распространенной среди новичков ошибкой, есть no such file or directory при попытке выполнить файл, скачанный из интернета. Сразу кажется что это бред, ведь файл существует, но на самом деле оболочка ищет только файлы с флагом исполняемый, а поэтому пока вы не установите этот флаг для файла, он для оболочки существовать не будет.

Проблемы в программах

Если ни с того ни с сего закрывается или не так, как требуется работает, какая-нибудь графическая программа, решение проблем linux начинается из запуска ее через терминал. Для этого просто введите исполняемый файл программы и нажмите Enter. Обычно достаточно начать вводить имя программы с маленькой буквы и использовать автодополнение для завершения ввода названия.

В терминале программа, скорее всего, покажет почему она не работает. Также у многих программ поддерживается опция -v или –verbose. Вы можете попробовать использовать эту опцию, если первый запуск в терминале ничего не дал. Далее, когда уже есть сообщение об ошибке, вы можете попытаться исправить его сами, если поняли в чем дело или попытаться найти решение на формуме, скорее всего, другие пользователи уже решили вашу проблему. Но если нет, вы можете создать новую тему и описать там свою ошибку. Но без вывода программы в терминале вам вряд ли помогут.

Многие ошибки системы linux, связанные с графической оболочкой вы можете найти в файле ~/.xsession-errors в вашей домашней директории. Если оболочка работает медленно, зависает или не работают другие программы, но в других логах причин этому нет, возможно, ответ находится именно в этом файле.

Также ошибки linux могут возникать не только в обычных программах но и в работающих в фоне сервисах.  Но их тоже можно решить, чтобы посмотреть сообщения, генерируемые сервисом, запущенным с помощью systemd, просто наберите команду просмотра состояния сервиса:

$ sudo systemctl status имя_сервиса

Дальше вы знаете, что делать с этой ошибкой, главное что у вас есть зацепка, а дальше все можно решить, ну или почти все.

Здесь, как и всегда большинство ошибок связано с тем, что что-то не установлено, какого-то файла нет или к чему-то невозможно получить доступ, тогда решение проблем linux не вызовет много забот.

Проблемы с драйверами и ядром

Проблемы с драйверами, модулями ядра или прошивками могут вызвать много неприятностей во время загрузки системы. Это может быть просто медленная загрузка системы, неработоспособность определенных устройств  неправильная работа видео или полная невозможность запустить графическую подсистему. Исправление ошибок Linux начинается с просмотра логов.

Вы можете посмотреть все сообщения ядра с момента начала загрузки, выполнив команду чтобы узнать какую linux выдает ошибку:

sudo dmesg

Чтобы иметь возможность удобно листать вывод можно выполнить:

sudo dmesg | less

Или сразу выбрать все ошибки:

sudo dmesg | grep error

Дальше будет очень просто понять какого драйвера не хватает, что система не может загрузить или что нужно установить. Если возникает ошибка ввода-вывода linux, то, скорее всего, драйвер несовместим с вашим устройством, в таком случае, может помочь обновление ядра, чтобы получить самую новую версию драйвера. В некоторых случаях ядро может само предложить вариант решения проблемы прямо в сообщении об ошибке вплоть до того какую команду выполнить или какой файл скачать. Если же нет, вы все еще можете воспользоваться поиском для решения своей проблемы linux.

Проблемы с графической оболочкой

Когда проблемы linux касаются графической оболочки, то решить их новичкам не так уж просто. Больше всего потому что доступен только терминал. Графическая оболочка может просто зависнуть или вовсе не запускаться, например, после обновления.

При проблемах с графической оболочкой вы можете всегда переключиться в режим терминала с помощью сочетания клавиш Ctrl+Alt+F1. Далее, вам нужно ввести логин и пароль, затем можете вводить команды терминала.

Посмотреть логи графической оболочки вы можете в том же файле ~/.xsession-erros.

Если проблема наблюдается после обновления до новой версии, то можно очистить кеш и удалить папку с настройками, обычно это помогает.

Проблемы с диском и файловой системой

Самая частая проблема с диском у новичков – это переполнение диска. Если под диск выделить очень мало места, то он переполнится и система не сможет создавать даже временные файлы, а это приведет к тому что все если не зависнет, то, по крайней мере, не сможет нормально работать.

Если это случилось, вам, скорее всего, придется переключиться в режим терминала и удалить несколько файлов. Вы можете удалять файлы логов или кэша пакетного менеджера. Много файлов удалять не нужно, достаточно освободить несколько мегабайт, чтобы прекратились ошибки системы linux и нормально работала графическая оболочка, а затем уже в ней решать все проблемы linux.

Выводы

Теперь исправление ошибок Linux будет для вас немного проще. Ошибки системы linux довольно сложная тема и этой информации явно мало, если у вас остались вопросы или есть предложения по улучшению статьи пишите в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Creative Commons License

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

I simply want to run an executable from the command line, ./arm-mingw32ce-g++, but then I get the error message,

bash: ./arm-mingw32ce-g++: No such file or directory

I’m running Ubuntu Linux 10.10. ls -l lists

-rwxr-xr-x 1 root root  433308 2010-10-16 21:32 arm-mingw32ce-g++

Using sudo (sudo ./arm-mingw32ce-g++) gives

sudo: unable to execute ./arm-mingw32ce-g++: No such file or directory

I have no idea why the OS can’t even see the file when it’s there. Any thoughts?

asked Oct 16, 2010 at 14:00

Warpspace's user avatar

This error can mean that ./arm-mingw32ce-g++ doesn’t exist (but it does), or that it exists and is a dynamically linked executable recognized by the kernel but whose dynamic loader is not available. You can see what dynamic loader is required by running ldd /arm-mingw32ce-g++; anything marked not found is the dynamic loader or a library that you need to install.

If you’re trying to run a 32-bit binary on an amd64 installation:

  • Up to Ubuntu 11.04, install the package ia32-libs.
  • On Ubuntu 11.10, install ia32-libs-multiarch.
  • Starting with 12.04, install ia32-libs-multiarch, or select a reasonable set of :i386 packages in addition to the :amd64 packages.

answered Oct 16, 2010 at 14:25

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

5

I faced this error when I was trying to build Selenium source on Ubuntu. The simple shell script with correct shebang was not able to run even after I had all pre-requisites covered.

file file-name # helped me in understanding that CRLF ending were present in the file.

I opened the file in Vim and I could see that just because I once edited this file on a Windows machine, it was in DOS format. I converted the file to Unix format with below command:

dos2unix filename # actually helped me and things were fine.

I hope that we should take care whenever we edit files across platforms we should take care for the file formats as well.

fantaghirocco's user avatar

answered Sep 23, 2015 at 9:29

Jitendra's user avatar

JitendraJitendra

6966 silver badges10 bronze badges

3

This error may also occur if trying to run a script and the shebang is misspelled. Make sure it reads #!/bin/sh, #!/bin/bash, or whichever interpreter you’re using.

answered Jan 27, 2014 at 20:24

Zoltán's user avatar

ZoltánZoltán

21.1k14 gold badges92 silver badges133 bronze badges

3

I had the same error message when trying to run a Python script — this was not @Warpspace’s intended use case (see other comments), but this was among the top hits to my search, so maybe somebody will find it useful.

In my case it was the DOS line endings (rn instead of n) that the shebang line (#!/usr/bin/env python) would trip over. A simple dos2unix myfile.py fixed it.

answered Feb 23, 2015 at 15:50

djlauk's user avatar

djlaukdjlauk

3,0991 gold badge12 silver badges12 bronze badges

1

I found my solution for my Ubuntu 18 here.

sudo dpkg --add-architecture i386

Then:

sudo apt-get update
sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386

answered May 15, 2020 at 15:37

betontalpfa's user avatar

betontalpfabetontalpfa

3,3841 gold badge32 silver badges65 bronze badges

1

As mentioned by others, this is because the loader can’t be found, not your executable file. Unfortunately the message is not clear enough.

You can fix it by changing the loader that your executable uses, see my thorough answer in this other question: Multiple glibc libraries on a single host

Basically you have to find which loader it’s trying to use:

$ readelf -l arm-mingw32ce-g++ | grep interpreter
  [Requesting program interpreter: /lib/ld-linux.so.2]

Then find the right path for an equivalent loader, and change your executable to use the loader from the path that it really is:

$ ./patchelf --set-interpreter /path/to/newglibc/ld-linux.so.2 arm-mingw32ce-g++

You will probably need to set the path of the includes too, you will know if you want it or not after you try to run it. See all the details in that other thread.

answered Jul 11, 2019 at 21:52

msb's user avatar

msbmsb

3,7393 gold badges30 silver badges38 bronze badges

2

I got this error “No such file or directory” but it exists because my file was created in Windows and I tried to run it on Ubuntu and the file contained invalid 15r where ever a new line was there.
I just created a new file truncating unwanted stuff

sleep: invalid time interval ‘15r’
Try 'sleep --help' for more information.
script.sh: 5: script.sh: /opt/ag/cont: not found
script.sh: 6: script.sh: /opt/ag/cont: not found
root@Ubuntu14:/home/abc12/Desktop# vi script.sh 
root@Ubuntu14:/home/abc12/Desktop# od -c script.sh 
0000000   #   !   /   u   s   r   /   b   i   n   /   e   n   v       b
0000020   a   s   h  r  n   w   g   e   t       h   t   t   p   :   /

0000400   :   4   1   2   0   /  r  n
0000410
root@Ubuntu14:/home/abc12/Desktop# tr -d \015 < script.sh > script.sh.fixed
root@Ubuntu14:/home/abc12/Desktop# od -c script.sh.fixed 
0000000   #   !   /   u   s   r   /   b   i   n   /   e   n   v       b
0000020   a   s   h  n   w   g   e   t       h   t   t   p   :   /   /

0000400   /  n
0000402
root@Ubuntu14:/home/abc12/Desktop# sh -x script.sh.fixed 

answered Jan 14, 2016 at 15:09

likeGreen's user avatar

likeGreenlikeGreen

1,0071 gold badge19 silver badges38 bronze badges

I got the same error for a simple bash script that wouldn’t have 32/64-bit issues. This is possibly because the script you are trying to run has an error in it. This ubuntu forum post indicates that with normal script files you can add sh in front and you might get some debug output from it. e.g.

$ sudo sh arm-mingw32ce-g++

and see if you get any output.

In my case the actual problem was that the file that I was trying to execute was in Windows format rather than Linux.

answered Nov 27, 2013 at 14:58

icc97's user avatar

icc97icc97

11k8 gold badges72 silver badges88 bronze badges

Below command worked on 16.4 Ubuntu

This issue comes when your .sh file is corrupt or not formatted as per unix protocols.

dos2unix converts the .sh file to Unix format!

sudo apt-get install dos2unix -y
dos2unix test.sh
sudo chmod u+x test.sh 
sudo ./test.sh

answered Apr 20, 2018 at 9:27

Soumyaansh's user avatar

SoumyaanshSoumyaansh

8,5567 gold badges44 silver badges44 bronze badges

I had the same problem with a file that I’ve created on my mac.
If I try to run it in a shell with ./filename I got the file not found error message.
I think that something was wrong with the file.

what I’ve done:

open a ssh session to the server

cat filename
copy the output to the clipboard

rm filename
touch filename
vi filename
i for insert mode
paste the content from the clipboard
ESC to end insert mode
:wq!

This worked for me.

answered Oct 12, 2014 at 21:44

space's user avatar

spacespace

211 bronze badge

1

Added here for future reference (for users who might fall into the same case):
This error happens when working on Windows (which introduces extra characters because of different line separator than Linux system) and trying to run this script (with extra characters inserted) in Linux. The error message is misleading.

In Windows, the line separator is CRLF (rn) whereas in linux it is LF (n). This can be usually be chosen in text editor.

In my case, this happened due to working on Windows and uploading to Unix server for execution.

answered Jan 24, 2020 at 2:54

PALEN's user avatar

PALENPALEN

2,7542 gold badges23 silver badges24 bronze badges

1

I just had this issue in mingw32 bash. I had execuded node/npm from Program Files (x86)nodejs and then moved them into disabled directory (essentially removing them from path). I also had Program Filesnodejs (ie. 64bit version) in path, but only after the x86 version. After restarting the bash shell, the 64bit version of npm could be found. node worked correctly all the time (checked with node -v that changed when x86 version was moved).

I think bash -r would’ve worked instead of restarting bash: https://unix.stackexchange.com/a/5610

answered Jul 15, 2016 at 8:31

Pasi Savolainen's user avatar

Pasi SavolainenPasi Savolainen

2,4501 gold badge22 silver badges35 bronze badges

I had this issue and the reason was EOL in some editors such as Notepad++. You can check it in Edit menu/EOL conversion. Unix(LF) should be selected.
I hope it would be useful.

answered Sep 22, 2019 at 12:04

user3184564's user avatar

1

Hit this error trying to run terraform/terragrunt (Single go binary).

Using which terragrunt to find where executable was, got strange error when running it in local dir or with full path

bash: ./terragrunt: No such file or directory

Problem was that there was two installations of terragrunt, used brew uninstall terragrunt to remove one fixed it.

After removing the one, which terragrunt showed the new path /usr/bin/terragrunt everything worked fine.

answered Dec 14, 2020 at 20:46

Pieter's user avatar

PieterPieter

1,88217 silver badges17 bronze badges

For those encountering this error when running a java program, it’s possible that you’re trying to run a 64-bit java program using on a 32-bit linux operating system.

I only realised when I ran ldd on 64-bit java which reported:

ldd /usr/java/jdk1.8.0_05/bin/java

‘not a dynamic executable’

Whereas the old 32 bit java reported sensible results:

ldd /usr/java/jdk1.8.0_05/bin/java

answered Jan 22, 2022 at 7:52

keithphw's user avatar

keithphwkeithphw

3801 gold badge4 silver badges14 bronze badges

In a .sh script, each line MUST end with a single character – newline (LF or “n“).

Don’t make mistakes like me, because my text-editor of choice is Notepad++ in Win.
The default line ending in Win is “rn” (CR LF), and such ending is not standard for Linux shell scripts.

answered Dec 16, 2022 at 22:20

Bokili Production's user avatar

In my case, it turns out the file was a symlink:

$ cat deluge-gtk.lock
cat: deluge-gtk.lock: No such file or directory
$ file deluge-gtk.lock
deluge-gtk.lock: broken symbolic link to 32309

Misleading errors like this are fairly common on Linux. Related discussion: https://lwn.net/Articles/532771/

answered Nov 2, 2021 at 5:01

Navin's user avatar

NavinNavin

3,6262 gold badges28 silver badges51 bronze badges

Give it a try by changing the name of file or folder which is not showing in terminal/command prompt.

step1 : change the name of file or folder.
step2 : cd filename/foldername

answered Nov 21, 2021 at 19:10

SHACHI PRIYA's user avatar

2

For future readers, I had this issue when trying to launch a Django server using gunicorn. I was using AWS CodeBuild to build the virtual environment and run tests and using CodeDeploy to put the built artifacts onto the production server and launch the new version (all environments were Ubuntu 20.04). I had mistakenly thought that env/bin/... contained actual binaries of native libraries but that was not the case. It was just Python scripts with a shebang of the path to the Python interpreter on the build machine. In my case, the machine installing the packages and actually running the packages was different. To be more specific, all of the files in env/bin had the shebang #!/codebuild/output/src715682316/src/env/bin/python, so of course running env/bin/gunicorn on the production server would fail. The cryptic error message was when Ubuntu would tell me that env/bin/gunicorn didn’t exist as opposed to saying /codebuild/output/src715682316/src/env/bin/python didn’t exist. I was able to fix this problem by starting gunicorn using python3 env/bin/gunicorn instead of env/bin/gunicorn.

answered May 22, 2022 at 20:17

Badr B's user avatar

Badr BBadr B

9001 gold badge8 silver badges14 bronze badges

This: sed -i -e 's/r$//' FILE, could potentially fix your problem.

As many answers already have explained, this issue could be caused by line endings being rn in Windows and only n in Linux. A suggested approach was to use dos2unix. As far as I understand this is not standard on most Linux distributions, and in my case I could not install / use it.

Therefore I used the following approach, (mentioned in Bash script – “/bin/bash^M: bad interpreter: No such file or directory”), where you can use the sed command instead.

sed -i -e 's/r$//' FILE where you replace FILE with the name of your file, e.g. sed -i -e 's/r$//' myscript.sh

If you for some reason do not have sed installed but do not want to use dos2unix you can use the following to install sed:

sudo apt-get update
sudo apt-get install sed

answered Mar 30 at 13:38

darclander's user avatar

darclanderdarclander

1,5061 gold badge12 silver badges35 bronze badges

1

Yet another possible reason: the file is a binary linked dynamically against musl (most likely for alpine)

on debian system you will have to install

apt-get update -y && apt-get install -y musl musl-dev musl-tools

answered Apr 14 at 11:15

Daniel Braun's user avatar

Daniel BraunDaniel Braun

2,35326 silver badges25 bronze badges

Unlike other operating systems such as Windows, Linux is an OS in which the majority of its tasks are performed using the Terminal. One of the major tasks that the Linux terminal performs is the execution of programs using commands. While attempting to execute any program through this method, the user may come across this very common error statement which is the “no such file or directory” issue.

This article will elaborate on the reasons that prompt the error “no such file or directory” and also provide possible solutions to fix it

How to Resolve the “no such file or directory”?

Since this is a very general error, there are a few different reasons that can invoke this issue on the system. All these reasons are discussed below in great detail.

Reason 1: Wrong File Name

The first and the most commonly occurring reason is caused by using incorrect spellings of the file name. For example, the mistake can be the incorrect spelling of a file. Below is an example of such a mistake:

$ bash sampl.sh

Solution: Check the File name and Path

In the example shown above, the bash file “sample.sh” is saved on the desktop. So, make sure that the error is not invoked by using the correct spellings and the correct path. Look at the following image where the name and path of the file are correct, and thus, the output is displayed:

$ bash sample.sh

Reason 2: Wrong File Format

The other most common cause behind this issue is that the file that is attempted to execute is in a different format than the operating system. Let’s take an example of this situation. The file that is executed using the command is a DOS file which is a script written for Windows. If this DOS file is executed in an Ubuntu system, the “no such file or directory” issue will be invoked.

Solution: Use the dos2unix Tool

There exists a very useful tool for exactly these types of scenarios. The dos2unix tool helps to convert a dos file to a script that can be read by the Ubuntu OS. The first step is to install the dos2unix tool using this command:

$ sudo apt install dos2unix

Once the tool is installed, convert the DOS file into an Ubuntu-compatible file using the following command:

$ dos2unix sample.dos

The system should be able to run the script file without the error being prompted after the conversion is complete.

Conclusion

The “no such file or directory” issue occurs when the name or the path of the executable file is entered incorrectly into the terminal. Another reason is that Ubuntu is not able to read the DOS script and if it is executed on the Ubuntu terminal, then the error is prompted. To fix these issues it needs to be made sure that the file path and file name are entered correctly into the terminal. The other fix is to install the dos2unix tool and convert the dos files format to run on Ubuntu. This article has demonstrated the reasons and the solutions to fix the error “no such file or directory”.

On Ubuntu, I get a ‘No such file or directory’ error when I try to execute a command.

I have checked with ls -la , the file adb is there and it has ‘x’ flag
So why I am getting a ‘No such file or directory’?

~/Programs/android-sdk-linux_x86/platform-tools$ ./adb
 bash: ./adb: No such file or directory
~/Programs/android-sdk-linux_x86/platform-tools$ ls -la
 total 34120
 drwxrwxr-x 3 silverstri silverstri     4096 2011-10-08 18:50 .
 drwxrwxr-x 8 silverstri silverstri     4096 2011-10-08 18:51 ..
 -rwxrwxr-x 1 silverstri silverstri  3764858 2011-10-08 18:50 aapt
 -rwxrwxr-x 1 silverstri silverstri   366661 2011-10-08 18:50 adb
 -rwxrwxr-x 1 silverstri silverstri   906346 2011-10-08 18:50 aidl
 -rwxrwxr-x 1 silverstri silverstri   328445 2011-10-08 18:50 dexdump
 -rwxrwxr-x 1 silverstri silverstri     2603 2011-10-08 18:50 dx
 drwxrwxr-x 2 silverstri silverstri     4096 2011-10-08 18:50 lib
 -rwxrwxr-x 1 silverstri silverstri 14269620 2011-10-08 18:50 llvm-rs-cc
 -rwxrwxr-x 1 silverstri silverstri 14929076 2011-10-08 18:50 llvm-rs-cc-2
 -rw-rw-r-- 1 silverstri silverstri      241 2011-10-08 18:50 llvm-rs-cc.txt
 -rw-rw-r-- 1 silverstri silverstri   332494 2011-10-08 18:50 NOTICE.txt
 -rw-rw-r-- 1 silverstri silverstri      291 2011-10-08 18:50 source.properties

Timo J.'s user avatar

asked Oct 9, 2011 at 2:52

michael's user avatar

2

It’s an executable file that misses required libraries. Use ldd to see what it needs, then provide these files.

answered Oct 9, 2011 at 9:39

Daniel Beck's user avatar

Daniel BeckDaniel Beck

109k14 gold badges286 silver badges333 bronze badges

1

Android SDK requires 32-bit libraries. You probably are on 64-bit and need the 32-bit libs. Here are the troubleshooting directions from developer.android.com

For Ubuntu 13.10 (Saucy Salamander) and above, install the libncurses5:i386, libstdc++6:i386, and zlib1g:i386 packages using apt-get:

sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install libncurses5:i386 libstdc++6:i386 zlib1g:i386

For earlier versions of Ubuntu, install the ia32-libs package using apt-get:

apt-get install ia32-libs

Hamy's user avatar

Hamy

2251 silver badge14 bronze badges

answered Nov 22, 2011 at 19:15

hoffmanc's user avatar

hoffmanchoffmanc

6511 gold badge4 silver badges4 bronze badges

4

sudo apt-get install --reinstall libc6-i386

is also need for me.

Tamara Wijsman's user avatar

answered Apr 12, 2012 at 14:55

Shawe's user avatar

ShaweShawe

411 bronze badge

1

I was also seeing the same after switching my machine from 32 bit ubuntu to 64 bit. Bash would report ‘No such file or directory’ of files that clearly existed with the execute attribute.

sudo apt-get install –reinstall libc6-i386

Fixed the problem. These are the “GNU C Library: 32-bit shared libraries for AMD64”

Seems like this is a bug in bash. Note that I also changed the default shell from dash to bash using

sudo dpkg-reconfigure dash

before I tried running the 32 bit executable. So I’m not sure if the problem would have happened with the default dash shell

answered Jul 24, 2013 at 19:01

user240504's user avatar

On a fresh Xubuntu 13.10 x64 install I got adb to run with:

sudo apt-get install --reinstall libc6-i386
sudo apt-get install libstdc++6:i386

And also zlib1g:i386 to make aapt work.

and if you still miss something use:

lld adb

answered Oct 21, 2013 at 1:49

Stéphane's user avatar

StéphaneStéphane

2461 silver badge6 bronze badges

2

For adb make sure you have the SDK unpacked and have run the SDK Manager to fully populate the SDK. Additionally make sure you have the following installed:
A.) JDK 6 or better
B.) lib32stdc++6
C.) lib32ncurses5

hoffmanc was the closest to getting it right, I don’t really understand why the answer from Daniel Beck is marked as correct when it’s not even close and has nothing to do with the problem.

Incidentally, if you try to run a truly non-existant command (i.e.:

# fakecommand

you’ll get: fakecommand: command not found, whereas in your situation the output you are seeing is actually coming from adb even though it’s not very clear that is the case.

answered Apr 14, 2012 at 18:00

Justin Buser's user avatar

Justin BuserJustin Buser

1,23711 silver badges14 bronze badges

Ubunto seems to have some issues with LSB compatibility, so try this if you are on Ubunto

apt-get install lsb

Note that ldd will sort of show that all the libraries are there, but they are not.

usmp-vm-lamp01$ ldd lmgrd
 linux-vdso.so.1 =>  (0x00007fffb33fe000)
 libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f10b0a48000)
 libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f10b074c000)
 libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f10b0535000)
 libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f10b0175000)
 libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f10aff71000)
 /lib64/ld-lsb-x86-64.so.3 => /lib64/ld-linux-x86-64.so.2 (0x00007f10b0c67000)
usmp-vm-lamp01$ locate libpthread.so.0
/lib/x86_64-linux-gnu/libpthread.so.0
usmp-vm-lamp01$ locate libm.so.6
/lib/x86_64-linux-gnu/libm.so.6
usmp-vm-lamp01$ locate /lib64/ld-lsb-x86-64.so.3
usmp-vm-lamp01$

answered Jun 9, 2014 at 21:26

Mark Lakata's user avatar

Mark LakataMark Lakata

8,0402 gold badges18 silver badges16 bronze badges

1

Добавить комментарий