- Unable to execute bash scripts even as root?
- Troubleshooting «Bash: Command Not Found» Error in Linux
- Fixing “bash: command not found” error
- Method 1: Double check the command name (no, seriously)
- Method 2: Ensure that the command is installed on your system
- Method 3: Make sure that the command is real, not an alias
- Method 4: Check if it is an executable script with correct path
- Adding it to the PATH
- Did it help you?
- Запуск Bash в деталях
- Диаграмма
- Login Shell?
- Интерактивный?
- В оболочке входа?
- В интерактивной оболочке?
- Ни один вариант?
- Типичные трудности и эмпирические правила
- Задания cron
- Скрипты, вызывающие друг друга
- Образ Docker в песочнице
Unable to execute bash scripts even as root?
That can happen if you have mounted the file system with the «noexec» option. You should remove it.
Also, to know quickly if your filesystem has been mounted with the ‘noexec’ option, use: mount And to remove the ‘noexec’ option, simply delete it from the list of options against the filesystem in the following file: /etc/fstab . Or alternatively add the ‘exec’ option to the end of the options.
The user option can cause this issue, as well. Removing it allowed me to execute the binary in question.
Another possible reason in Ubuntu can be the default file manager behavior. Go to filemanager->edit->prefferences->behavior and check execute on double click
Script needs be executable. Use this:
This duplicates another answer from several years back. It’s probably a common beginner problem, but this particular instance of this answer shouldn’t deserve more upvotes than the original, especially since the question already mentions the original OP had already made sure the permissions were correct.
Although not directly pertinent to this particular thread; if a file has come form a Windows system there may be a CR/LF at the end of the line. This would affect all lines in the file, including the initial execution line, and would not be visible if you are viewing the file.
$ ./test.sh -bash: ./test.sh: /bin/bash^M: bad interpreter: No such file or directory
To see this, you could cat -A the file: $ cat -A ./test.sh #!/bin/bash^M$ echo «me»^M$
to see the actual rights and ownership of the file. To see if the chmod command actually worked. You might want to change the ownership along with the mod of the file check : http://www.tuxfiles.org/linuxhelp/fileowner.html
Use chmod +x ./test.sh this should allow you to run it.
Also, check to see if the directory/filesystem containing the script is nfs-mounted. root won’t run scripts from nfs-mounted locations.
In macOS this can occur if a com.apple.quarantine flag exists. If you see a @ suffix on the permissions after running a ls -l on the script’s path, execute ls -l@ *script_path* to confirm. Then run a xattred -d com.apple.quarantine *script_path* to remove the quarantine flag.
you need use ./test.sh when you in the directory of that file,if you don’t,try PATH TO THE SCRIPT .or you can copy it to some directory of /data and chmod it for shell,then do the above steeps.if you still fail,it’s ok because i have a same problem,i just did it success for once time.
if you are root user and still have that problem,so your shell is broken.i know that because i couldn’t execute many commands of the sh shell(similar to bash) even i tried as root and it said permission denied like your,i couldn’t change the permission.then i tried to copy them to my directory in /data ,change permission and i could use commands again.but when i try to execute the script,it’s no such file or directory.
Troubleshooting «Bash: Command Not Found» Error in Linux
This beginner tutorial shows how to go about fixing the Bash: command not found error on Debian, Ubuntu and other Linux distributions.
When you use commands in Linux, you expect to see an output. But sometimes, you’ll encounter issues where the terminal shows ‘command not found’ error. There is no straightforward, single solution to this error. You have to do a little bit of troubleshooting on your own. It’s not too difficult, honestly. The error gives some hint already when it says “bash: command not found”. Your shell (or Linux system) cannot find the command you entered. There could be three possible reasons why it cannot find the command:
- It’s a typo and the command name is misspelled
- The command is not even installed
- The command is basically an executable script and its location is not known
Let’s go in detail on each possible root cause.
Fixing “bash: command not found” error
Method 1: Double check the command name (no, seriously)
It is human to make mistakes, specially while typing. It is possible that the command you entered has a typo (spelling mistake).
You should specially pay attention to:
- The correct command name
- The spaces between the command and its options
- The use of 1 (numeral one), I (capital i) and l (lowercase L)
- Use of uppercase and lowercase characters
Take a look at the example below, where I have misspelled the common ls command.
So, make double sure what you are typing.
Method 2: Ensure that the command is installed on your system
This is another common reason behind the command not found error. You cannot run a command if it is not installed already.
While your Linux distribution comes with a huge number of commands installed by default, it is not possible to pre-install all the command line tools in a system. If the command you are trying to run is not a popular, common command, you’ll have to install it first.
You can use your distribution’s package manager to install it.
In some cases, popular commands may get discontinued and you may not even install it anymore. You’ll have to find an alternative command to achieve the result.
Take the example of ifconfig command. This deprecated command was used for getting Ip address and other network interface information. Older tutorials on the web still mention using this command but you cannot use it anymore in newer Linux versions. It has been replaced by the ip tool.
Occasionally, your system won’t find even the extremely common commands. This is often the case when you are running a Linux distribution in Docker containers. To cut down on the size of the operating system image, the containers often do not include even the most common Linux commands.
This is why Docker user stumble across things like ping command not found error etc.
So, the solution is to either install the missing command or find a tool that could do the same thing you were trying to do with the missing command.
Method 3: Make sure that the command is real, not an alias
I hope you are aware of the alias concept in Linux. You can configure your own shorter commands to replace the typing of a longer command.
Some distributions like Ubuntu automatically provide commands like ll (which is aliased to ls -l), la (aliased to ls -a) and so on.
Imagine that you are used to of typing ll and la on your personal system and you log on to another Linux system and find that ll command does not exist. You cannot even install the ll command because it is not a real command.
So, if you cannot find a command and it cannot even be installed, you should try searching on the internet if that command even exists. If it does not, probably it was an alias on some other system.
Method 4: Check if it is an executable script with correct path
This is a common mistake Linux rookies make while running a shell script.
Even if you are in the same directory and try to run an executable script just by its name, it will show an error.
[email protected]:~/scripts# sample -bash: sample: command not found
You need to either specify the shell interpreter explicitly or its absolute path.
If you are in some other directory and try to execute the shell script without giving the correct path to the file, it will complain about not finding the file.
Adding it to the PATH
In some cases, you download the entire software in a tar file, extract it and find an executable file along with other program files. To run the program, you need to run the executable file.
But for that, you need to be in the same directory or specify the entire path to the executable file. This is tiresome.
Here, you can use the PATH variable. This variable has a collection of directories and these directories have the binary (executable) files of various Linux commands. When you run a command, your Linux system checks the mentioned directories in the PATH variable to look for the executable file of that command.
You can check the location of the binary of a command by using the which command:
If you want to run an executable file or script from anywhere on the system, you need to add the location of the file to this PATH variable.
The PATH variable then needs to be added to the rc file of the shell so that the changes made to PATH variable are permanent.
You get the gist here. It is important that your Linux system has knowledge about the location of the executable script. Either you give the path while running it or you add its location to the PATH variable.
Did it help you?
I understand that when you are new to Linux, things could be overwhelming. But when you understand the root cause of the problem, it gradually improved your knowledge.
Here, there is no straightforward solution possible for the ‘command not found error’. I gave you some hints and pointers and that should help you in troubleshooting.
Similarly, you may encounter ‘unable to locate package’ error in Ubuntu. Here’s what you need to know about it.
If you still have doubts or need help, please let me know in the comment section.
Запуск Bash в деталях
Если вы нашли эту страницу в поиске, то наверняка пытаетесь решить какую-то проблему с запуском bash.
Возможно, в вашем окружении bash не устанавливается переменная среды и вы не понимаете, почему. Возможно, вы засунули что-то в различные загрузочные файлы bash или в профили, или во все файлы наугад, пока это не сработало.
В любом случае, смысл этой заметки — как можно проще изложить процедуру запуска bash, чтобы вы могли справиться с проблемами.
Диаграмма
Эта блок-схема обобщает все процессы при запуске bash.
Теперь подробнее рассмотрим каждую часть.
Login Shell?
Сперва нужно выбрать, находитесь вы в командной оболочке входа (login shell) или нет.
Оболочка входа — это первая оболочка, в которую вы попадаете при входе в систему для интерактивного сеанса. Оболочка входа не требует ввода имени пользователя и пароля. Вы можете форсировать запуск оболочки входа, добавив флаг —login при вызове bash , например:
Оболочка входа настраивает базовую среду при первом запуске оболочки bash.
Интерактивный?
Затем вы определяете, является оболочка интерактивной или нет.
Это можно проверить по наличию переменной PS1 (она устанавливает функцию ввода команд):
if [ "$" ]; then echo interactive else echo non-interactive fi
Или посмотреть, установлен ли параметр -i , с помощью специальной переменной дефиса — в bash, например:
Если в выдаче есть символ i , то оболочка является интерактивной.
В оболочке входа?
Если вы находитесь в оболочке входа, то bash ищет файл /etc/profile и запускает, если он существует.
Затем ищет любой из этих трёх файлов в следующем порядке:
~/.bash_profile ~/.bash_login ~/.profile
Когда находит один, то запускает его и пропускает другие.
В интерактивной оболочке?
Если вы находитесь в интерактивной оболочке без входа в систему (non-login shell), предполагается, что вы уже побывали в оболочке входа, окружение настроено и будет унаследовано.
В этом случае выполняются по порядку следующие два файла, если они существуют:
Ни один вариант?
Если вы не находитесь ни в оболочке входа, ни в интерактивной оболочке, то ваше окружение действительно будет пустым. Это вызывает большую путаницу (см. ниже о заданиях cron).
В этом случае bash смотрит на переменную BASH_ENV вашей среды и выполняет соответствующий файл, который там указан.
Типичные трудности и эмпирические правила
Задания cron
У меня в 95% случаев отладка запуска bash связана с тем, что задание cron работает не так, как ожидалось.
Эта проклятая задача работает нормально, когда я запускаю её в командной строке, но фейлится при запуске в crontab.
- Задания cron не являются интерактивными.
- В отличие от скриптов в командной строке, задания cron не наследуют среду оболочки.
Вот почему зачастую приходится установить конкретный PATH для задачи cron, как здесь:
* * * * * PATH=$:/path/to/my/program/folder myprogram
Скрипты, вызывающие друг друга
Ещё одна распространенная проблема, когда скрипты по ошибке настроены на вызов друг друга. Например, /etc/profile обращается к ~/.bashrc .
Обычно так происходит, когда кто-то пытался исправить какую-то ошибку и вроде бы всё заработало. К сожалению, когда нужно разделить эти разные типы сессий, то возникают новые проблемы.
Образ Docker в песочнице
Чтобы поэкспериментировать с запуском оболочки, я создал образ Docker, который можно использовать для отладки запуска оболочки в безопасной среде.
$ docker run -n bs -d imiell/bash_startup $ docker exec -ti bs bash
Для принудительного логина и имитации оболочки входа:
Для проверки набора переменных BASH_ENV :
Для отладки crontab каждую минуту выполнятся простой скрипт (в /root/ascript ):
$ crontab -l $ cat /var/log/script.log