Command not found linux что делать
Перейти к содержимому

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

  • автор:

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

Apt-get — это пакетный менеджер, который используется по умолчанию в семействе дистрибутивов Debian и Ubuntu. Учитывая, что это пакетный менеджер, один из почти самых основных пакетов системы, то логично, что программа должна присутствовать в каждом дистрибутиве. Но все же некоторые пользователи встречаются с ошибкой apt get command not found.

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

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

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

  • Одна из самых очевидных причин, получения ошибки «apt get не найдена» в том, что у вас не Ubuntu. Этот пакетный менеджер используется только в дистрибутивах Linux, основанных на Debian. Системы Red Hat, CentOS, Fedora, OpenSUSE, CoreOS, Cloud Linux, ArchLlinux и другие таковыми не являются. Они имеют собственный пакетный менеджер, у каждой свой и именно его нужно использовать для установки пакетов, а не искать apt.
  • Если вы используете команду apt, а не apt-get, то, возможно, у вас старый дистрибутив, который не поддерживает такого синтаксиса, используйте apt-get;
  • Вторая причина в том что вы случайно или намерено удалили пакет Apt. Его больше нет в системе поэтому система и не может его найти;
  • Третья причина, может быть в невозможности обнаружения программы. Утилита apt есть в системе и исправно работает, но вы повредили переменную среды PATH и теперь система не ищет исполняемые файлы в той папке где находится apt.

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

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

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

ls -l /usr/bin/apt-get

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

chmod +x /usr/bin/apt-get

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

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

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

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

Для Ubuntu Xenial:

Для Ubuntu Yakkety:

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

sudo dpkg -i apt*

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

Выводы

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

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

Troubleshooting "Bash: Command Not Found" Error in Linux

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.

bash 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

bash command not found error 1

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.

command not found error

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.

command not found debian

You may have to install the missing command

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.

ifconfig command not found

Some popular commands get discontinued over the time

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.

ping command not found ubuntu

Docker containers often have only a few commands installed

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.

alias in ubuntu

Alias in Ubuntu desktop

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.

You need to either specify the shell interpreter explicitly or its absolute path.

bash script command not found error

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.

script file not found error

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:

path location

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.

adding executable to path variable linux

The PATH variable then needs to be added to the rc file of the shell so that the changes made to PATH variable is permanent.

You get the gist here. It is important that your Linux system has the 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.

If you still have doubt or need help, please let me know in the comment section.

How to fix Bash: Command Not Found Error in Linux

The command not found error is one of the most common errors in Linux. The cause of the occurrence of this error is the system’s inability to find the file which you have mentioned in your path variable.

What is a path variable?

The path variable will tell our Linux system about the places to look for certain files or commands. The path variable generally contains paths such as /usr/local/sbin, /usr/bin, /usr/local/bin, etc. Normally we do not specify the path variable each time, because it is pre-configured to look for programs in all the directories.

Now that we know a little bit about the path variable let us see how we can resolve the command not found error.

Different ways to fix this error:

1. Installing the package which is not present:

Sometimes when we write a command in Linux, the system is unable to find it because it is simply not present on our system. For example, we will try to run python which is not installed in our system

You can see the command not found error, to resolve this simply install python.

Now when you will type python, the error will be gone.

2. Explicitly telling bash where to look:

Sometimes, especially for scripts, we do not have to rely on the path we just execute them right away, so that they are executed wherever they are. We do this by putting “./” in front of them. We have created a script named GFG, let us execute it.

But if we do not include the “./” before the script name then it gives us the command not found error. Let us see this from an example. We will create another script “Sample.sh” and try to execute it.

You can see that it is giving us the same error, we will resolve it in the next step.

3. Modifying the path variable:

Understanding Environment variables

These are the variables that are necessary to set up the environment of a Linux shell. These reside in the child process of the shell variables. These are of two types local and global. The standard convention for writing an environment is to write it in capital letters preceded by a “$” symbol. For example, the $PATH variable. In layman’s terms with the help of these variables, we can modify the way in which the applications work on our system.

Let us understand the PATH environment variable:

With the help of this variable, we can specify the directory whenever we need to find a command. The default value of this variable is stored in the /etc/profile file. We do not type the entire path of the command every time, that is because the $PATH variable is configured in such a way that it tells the system where to look for that command.

For us, to be able to run the “Sample.sh” script simply by writing it we are going to add it to the Path variable. Let us first see all the Paths. Use the below command to see the path:

We are currently in the /home/mukul directory and it is not recommended to add the home directory to the path. So we will create a bin folder(which will contain the Sample.sh script) and concatenate it to the path variable. Type the below commands to create a bin folder and move the Sample.sh into it.

Adding a directory to the PATH variable

By default there are a lot of different directories which are present in this variable, we can also add our own directory into the PATH variable which will enable us to run our script or command from anywhere in the system. This definitely saves a lot of time and effort. There are two ways in which we can add to PATH:

  1. By appending (This adds our path at the end of the PATH variable)
  2. By prepending( This adds our path at the beginning of the PATH variable)

Now we have to attach the /home/mukul/bin to the path, use the below command:

export PATH = $PATH: /home/mukul/bin (appending)

export PATH = /home/mukul/bin :$PATH (prepending)

You can see that our path has been added to the path variable.

Now we can run our “Sample.sh” script from anywhere and that too without any path or “./” mentions.

Note: Make sure to give permission to your file, or else it will give an error.

4. You have misspelled the command:

We all make mistakes and that is a natural thing, this error can also arise when we type the command incorrectly.

For example, If we type PQD instead of PWD we will get this error.

So these were the four ways in which you can get rid of the Bash: Command Not Found Error in Linux.

Command not found when using sudo

Rob Kielty's user avatar

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.

To read the chmod documentation for your local system , run man chmod or info chmod from the command line. Once read and understood you should be able to understand the output of running .

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

Owner has read and write access rw but the — indicates that the executable permission is missing

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.

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

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