command not found linux что делать

Как исправить — bash: python: command not found Error

В этом руководстве показано, как исправить ошибку — bash: python: command not found. Давайте посмотрим, как решить эту проблему.

1. Проверьте Установленный Python

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

Выполните следующие команды, чтобы найти установленное местоположение python.

или введите команду

python3 is /usr/bin/python3python3 is /bin/python3

или выдаст такой ответ:

Следующая команда проверит версии python:

Простая команда run python3:

$ python3
Python 3.8.2 (default, Jul 16 2020, 14:00:26)
[GCC 9.3.0] on linux
Type «help», «copyright», «credits» or «license» for more information.

Если python у вас не установлен, то в следующем разделе я покажу вам, как установить python.

Установите Python на Ubuntu/Debian

Debian и Ubuntu, а так же их производные дистрибутивы поставляются с предустановленным python. В случае, если он поврежден или не установлен, используйте следующую команду.

Примечание: приведенная выше команда установит python версии 2.

Python 2 После 1 января 2020 года Python 2 больше не получает никаких обновлений и не рекомендует его использовать.

Чтобы установить python 3, Введите команду:

Python установленный из исходного кода, по умолчанию устанавливается в ‘http://usr/local/bin/’. В этом случае ввод python на консоли будет выполняться не внутри файла /usr/local/bin/, а внутри файла /usr/bin/.

Если вы хотите выполнить его внутри файла /usr/local/bin/, вы можете легко настроить систему, используя псевдоним (алиас). Псевдоним должен быть помещен в файл. bashrc, как показано ниже.

Установите Python на Fedora

Благодаря менеджеру пакетов dnf вы можете легко установить python на Fedora с помощью:

Установите Python на RHEL/CentOS

Чтобы установить Python на RHEL, Oracle Linux и CentOS, используйте команду yum следующим образом:

Установите Python на Arch Linux

В Arch Linux выполните следующую команду для установки python:

2. Проверьте путь переменной окружения

Каждый раз, когда пользователь запускает команду на консоли, машина ищет ее местоположение или адрес в списке предопределенных каталогов. Которые хранятся в переменной окружения PATH.

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

Переменная окружения PATH может быть временно изменена для текущего сеанса терминала или навсегда.

Для отображения содержимого переменной окружения PATH на консоли требуется ввести команду:

Ответ терминала будет следующим:

Убедитесь, что установленный путь python добавлен в переменную PATH. Вы можете увидеть в приведенных выше выходных данных ‘/usr/bin’ и ‘/bin’ это пути для python 3. Так что они присутствуют. Чтобы сделать его постоянным, обязательно экспортируйте переменную PATH в

/.bash_profile или в соответствующий конфигурационный файл, который запускает оболочку.

3. Проверка Сломанной Символической Ссылки

При запуске скрипта python вы можете понять, что символическая ссылка на исполняемые файлы Python указана неправильно.

Для указания /usr/bin/python на /usr/local/bin/python3.9 введите в терминал:

Заключение

Благодаря этой статье мы узнали, как правильно исправить ошибку — bash: python: command not found в вашей ОС Linux.

Источник

Linux Command Not Found: This Will Fix It

Are you using Linux and you have seen the “Command Not Found” error while trying to execute a command? It’s time to find out why.

We will look at this error together and understand how to fix it.

What is the cause of the command not found error?

The “Command not found” error is caused by the fact that Linux is unable to find on your system a command you try to execute. When you run a command Linux looks for binaries in the list of directories specified in the PATH environment variable, this allows you to execute a command without specifying its full path.

In this article we will go through an example of this error and I will show you how to fix it.

You will also understand how Linux (or Unix-like systems) look for commands when a user executes them.

The PATH Environment Variable

Linux system are configured with a pre-defined set of environment variables required by the operating system to function properly.

The PATH environment variable is one of the most important environment variables in a Linux system. It contains a list of directories used by Linux to search for commands that can be executed without specifying their full path.

You can use the echo command to see the value of the PATH variable:

In the list of directories inside the PATH you can see the home directory for my current user (ec2-user) but also directories like /usr/bin.

Let’s have a look at some of the commands present in the /usr/bin directory. To restrict the list of commands returned by ls, I just look for commands starting with ch (I use the ch* wildcard to do that):

Let’s take the chmod command as an example.

If I use the which command to check the full path of the chmod command I get the following:

As you can see this is exactly the same directory in the PATH, /usr/bin.

The fact that /usr/bin/ is in the PATH allows us to execute the chmod command withouth having to specify its full path.

Where Is PATH Defined in Linux?

Wondering where is the PATH environment variable defined?

It’s usually defined somewhere in your home directory, and specifically in one of the hidden files used in Linux to configure your user environment: the .bashrc file.

As you can see the PATH variable is defined and it’s then made available to any child processes of this shell using the export command.

This is a common requirement if you download external tools that are not part of the Linux operating system and you want to be able to execute them from your shell without having to specify their full path.

One common scenario is adding Java to the Linux PATH after downloading the JDK (Java Development Kit) on your system.

PATH Configured At System-Wide Level

When I see the value of the PATH variable on my system, here’s what I get:

There’s something that doesn’t make sense to me…

They must be defined somewhere at system level and not just at user level.

In Linux, system-wide configuration files are located under the /etc directory. For example in /etc/bashrc.

Let’s find out where this initial value for the PATH comes from using a recursive grep as root under the /etc directory.

The only result is in the configuration file for the SSH deamon. According to a comment in this file, the daemon is compiled with the PATH set to the value I’m seeing on my system.

That’s where the value of the PATH comes from!

How Do I fix the Bash error “command not found”?

So far we have seen what the PATH is…

…but how does it help us fix the command not found error?

First of all, before looking at how the command not found error could be related to the PATH, let’s look at a simple cause.

Before doing any other checks make sure you are not misspelling the command when you execute it.

This might be happening mostly to those who are new to Linux and are learning the commands.

If the way you have typed the command is correct, then keep going…

Scenario 1 can occur if you download a specific tool on your Linux system and you don’t add the directory in which the binary is located to the PATH environment variable.

Let’s say the current value of the PATH is:

And I want to add the directory /opt/install to it because that’s where the command I want to execute is located. That line would become:

The order of the directories in the PATH is important, the first directory has higher priority than the second directory, and so on.

So, if you want the /opt/install directory to be the first one to be searched when a command is executed the PATH definition becomes:

In the next section we will look at the scenario 2, where the command is not available on your Linux system.

Running a Command Not Available on the System

Now, let’s have a look at what happens when we execute a command that is not available on a Linux system.

I take, for example, the rsync command:

How do I know if I’m seeing the “command not found” error because the rsync command is not in the PATH or because it doesn’t exist on the system at all?

I can use the package manager of my Linux distribution. In this case I’m using CentOS and hence I will use the yum command to see if the rsync package is installed:

This command doesn’t return any results, this means rsync is not available on the system.

Another option is to use the RPM command to query the RPMs installed on my Linux system:

Once again, no results for the rsync package.

So, let’s install it!

The yum search command returns a result for rsync:

And we can install the rsync package using the “yum install” command:

And now if I try to execute the rsync command again to check its version:

The command works well!

Conclusion

I have also explained how the PATH environment variable works and how important is for a Linux system.

Have you managed to find what’s causing this error in your system?

Источник

Скрипт Bash всегда печатает » команда не найдена»

каждый раз, когда я запускаю скрипт с помощью bash scriptname.sh из командной строки в Debian, я получаю Command Not found и затем результат сценария. Таким образом, скрипт работает, но всегда есть Command Not Found заявление печатается на экране.

я запускаю скрипт из /var папка.

я запускаю его, набрав следующее:

UPDATE-проблема появляется в пустых строках. Каждая пустая строка приводит к команда не найдена. Почему это произошло?

16 ответов

убедитесь, что первая строка:

введите путь к bash, если это не /bin/bash

другой способ узнать, находится ли ваш файл в dos/Win формат:

результат будет выглядеть примерно так:

это выведет весь текст файла с отображается для каждого \r символ в файл.

Как @artooro добавил в комментарий:

чтобы исправить эту проблему, запустите chmod +x testscript.sh

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

если, как вы говорите, это пустые строки, вызывающие проблемы, вы можете проверить, что actaully на них. Беги:

и убедитесь, что нет» невидимых » смешных персонажей, таких как CTRL-M (возврат каретки) вы можете получить с помощью редактора типа Windows.

использовать dos2unix в файле сценария.

попробовать chmod u+x testscript.sh

для выполнения этого необходимо указать полный путь например

была такая же проблема. К сожалению

Так что я сделал это, чтобы преобразовать.

проблемы с запуском скриптов также могут быть связаны с плохим форматированием многострочных команд, например, если у вас есть пробел после разрыва строки «\». Е. Г. это:

(обратите внимание, что дополнительное пространство после»\») вызовет проблемы, но когда вы удалите это пространство, оно будет работать отлично.

Это может быть тривиально и не связано с вопросом OP, но я часто ошибался в начале, когда я изучал сценарии

это вызовет ответ «команда не найдена». Правильный способ-устранить пробелы

, который, в Vim, выглядел так:

только после запуска bash script checker shellcheck Я нашел проблему.

на Bash для Windows я попытался неправильно запустить

для людей с фоном Windows правильная форма выглядит избыточной:

Источник

Command not found when using sudo

I have a script called foo.sh in my home folder.

Why does this happen and how I can fix it?

command not found linux что делать. Смотреть фото command not found linux что делать. Смотреть картинку command not found linux что делать. Картинка про command not found linux что делать. Фото command not found linux что делать

10 Answers 10

Permission denied

In order to run a script the file must have an executable permission bit set.

In order to fully understand Linux file permissions you can study the documentation for the chmod command. chmod, an abbreviation of change mode, is the command that is used to change the permission settings of a file.

. which will list the READ, WRITE and EXECUTE permissions for the file owner, the group owner and everyone else who is not the file owner or a member of the group to which the file belongs (that last permission group is sometimes referred to as «world» or «other»)

Here’s a summary of how to troubleshoot the Permission Denied error in your case.

The chmod command fixes that. (Group and other only have read permission set on the file, they cannot write to it or execute it)

foo.sh is now executable as far as Linux is concerned.

Using sudo results in Command not found

When you run a command using sudo you are effectively running it as the superuser or root.

The reason that the root user is not finding your command is likely that the PATH environment variable for root does not include the directory where foo.sh is located. Hence the command is not found.

The PATH environment variable contains a list of directories which are searched for commands. Each user sets their own PATH variable according to their needs. To see what it is set to run

Here’s some sample output of running the above env command first as an ordinary user and then as the root user using sudo

Note that, although similar, in this case the directories contained in the PATH the non-privileged user (rkielty) and the super user are not the same.

Источник

Ошибка apt-get command not found

В этой статье мы рассмотрим почему возникает такая ошибка, как это вообще может быть и как исправить apt get команда не найдена.

Что значит apt get команда не найдена?

command not found linux что делать. Смотреть фото command not found linux что делать. Смотреть картинку command not found linux что делать. Картинка про command not found linux что делать. Фото command not found linux что делать

Фактически это сообщение об ошибке означает как раз то, что оно нам сообщает, команда, которую вы пытаетесь выполнить не найдена в системе. Она либо еще не была установлена, либо была удалена. Но все это звучит очень странно в отношении к менеджеру пакетов. Рассмотрим основные причины возникновения ошибки:

Теперь рассмотрим как решить проблему. Это очень просто.

Как исправить apt get команда не найдена?

Поскольку вторая причина предполагает меньше действий, нам нужно сначала проверить ее. Обычно исполняемые файлы apt находятся в каталоге /usr/bin. Сначала посмотрим есть ли такой файл в той папке:

command not found linux что делать. Смотреть фото command not found linux что делать. Смотреть картинку command not found linux что делать. Картинка про command not found linux что делать. Фото command not found linux что делать

Если файл есть, то вы увидите что-то похожее как на снимке выше. Также обратите внимания на права. Для пользователя, группы и остальных должен быть выставлен флаг «x» означающий исполнение. Если же его нет, то apt придется переустановить. Если права отличаются от приведенных выше, а именно «-rwxr-xr-x», то их тоже нужно исправить, добавим для всех категорий флаг исполняемости:

chmod +x /usr/bin/apt-get

Если предыдущие варианты не сработали проверим содержимое переменной среды PATH:

command not found linux что делать. Смотреть фото command not found linux что делать. Смотреть картинку command not found linux что делать. Картинка про command not found linux что делать. Фото command not found linux что делать

Вы должны увидеть в ней ссылку на /usr/bin. Если такой строчки нет, то проблема была здесь, а строчку нужно добавить в конец:

Если вы вносили изменения в файл /etc/profile, и переменная PATH сломалась из-за этого, то нужно внести исправления и в этот файл.

command not found linux что делать. Смотреть фото command not found linux что делать. Смотреть картинку command not found linux что делать. Картинка про command not found linux что делать. Фото command not found linux что делать

Последний вариант, если ничего не помогло, это переустановить утилиту. Мы просто скачаем ее из официального сайта и установим в систему. Только нужно выбирать версию для своей операционной системы. Вы можете скачать пакет с помощью браузера или таких команд:

Для Ubuntu Yakkety:

Теперь осталось установить загруженный пакет:

Готово, после этого ошибка apt get command not found должна исчезнуть и вы сможете нормально работать со своими пакетами.

Выводы

В этой статье мы рассмотрели почему не работает apt get, из-за чего возникает ошибка apt get команда не найдена, а также как ее решить. Надеюсь, приведенная здесь информация была полезной для вас.

Источник

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

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