When you’re trying to run a command (with or without sudo
) and get an error message that reads «Command not found,» this means the script or file you’re trying to execute doesn’t exist in the location specified by your PATH variable. What is this variable, and how can you run commands that it can’t find?
[ Related reading: Understand file paths and how to use them in Linux ]
Understanding environment variables
In computing, a variable is a placeholder for a value that can change. You use variables every day in normal speech, although you don’t think of them as such. When you say «my laptop,» you’re using «laptop» as a generic variable or placeholder for the computer you’re carrying, regardless of whether it happens to be a Lenovo, Mac, or a Raspberry Pi in a fancy case.
Environment variables are special variables that contain information about your login session. Many of these variables are set by default during installation or user creation. They’re stored for the system shell, applications, and scripts to use when executing commands.
There are global, or system-defined, variables and local, or user-defined, variables.
Global variables
Global variables come predefined in your login shell, but they aren’t immutable and can be modified or deleted according to your preferences. You can use the printenv
or env
commands to display the environment variables on your system:
$ env
SHELL=/bin/bash
SESSION_MANAGER=local/kiwi.homelinux.local:@/tmp/.ICE-unix/1906,unix/kiwi.homelinux.local:/tmp/.ICE-unix/19
06
WINDOWID=153092103
COLORTERM=truecolor
XDG_CONFIG_DIRS=/home/tux/.config/kdedefaults:/etc/xdg:/etc/kde/xdg
LESS=-XR
XDG_SESSION_PATH=/org/freedesktop/DisplayManager/Session1
HISTCONTROL=:ignorespace:ignoredups:ignorespace:ignoredups
PKG_CONFIG_PATH=/usr/local/lib64/pkgconfig:/usr/local/share/pkgconfig:/usr/lib64/pkgconfig:/usr/share/pkgconfig
[...]
The env
command prints out all global environment variables. Variables are case sensitive, and all Linux distributions use uppercase for environment variable names by default.
[ Keep your favorite Git commands, aliases, and tips close at hand. Download the Git cheat sheet. ]
Local variables
A local variable exists only within a specific shell. Therefore, when you define a local variable, it’s only available in your current shell. It doesn’t propagate or persist to a new shell session unless you export it as a global variable.
Local variables are often defined in lowercase to avoid overwriting a global variable with the same name.
The PATH environment variable
The PATH global environment variable lists the directories your system searches for valid, executable commands. By default, it contains standard directories that normally store executables like /usr/bin
, /usr/local/bin
, and so on.
When you type in a command, such as grep
or vim
, your system searches through all directories listed in your PATH variable, in the order that they’re listed, until it finds an executable file by the same name. Should it fail to find one, it issues the «Command not found» error.
$ printenv PATH
/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/tux/.local/bin:/home/tux/bin
$ env $PATH
env: /usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/tux/.local/bin:/home/tux/bin
5 ways to fix «Command not found» errors
There are several ways to fix this problem. Here are five of them.
1. Include the path
Not everything you want to execute needs to be in your path. You can execute files directly by specifying the path to the file you want to run. By identifying the file’s location, you circumvent the need for your system to search your path at all.
For example, suppose you have a script called hello
that you want to run. It’s located in your home directory, and you have already marked it as executable with chmod +x
:
$ ~/hello
hello world
By telling your system the file’s location, the PATH variable is never involved, and the file runs as expected.
2. Add a new path
Alternately, you can add a new directory to your PATH. Add your executable files to that directory, and then you can run them without manually providing a path:
$ cp ~/hello ~/.local/bin
$ export PATH=$PATH:$HOME/.local/bin
$ printenv PATH
/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/tux/.local/bin
You may want to add the new PATH environment variables to your login shell by including them in your .bashrc
file as new settings.
[ Download now: A sysadmin’s guide to Bash scripting. ]
3. Copy a file to an existing path location
If you want to execute your binary file or script, copy it to any of the directory paths already listed in the PATH environment variable:
$ sudo cp ~/hello /usr/local/bin/
$ hello
hello world
4. Tell Bash where to look
Probably the simplest option, especially for one-off scripts or applications, is to tell Bash not to consider the PATH but rather to «look here.» Do this by placing a dot and a slash in front of the command, script, or application name. For the hello
script, it looks like this:
$ sudo ./hello
hello world
No permanent changes are made to the system. This might be handy if you’re writing a script and want to test it before copying or moving it to its normal storage location (presumably along the PATH).
5. Install a package
Sometimes when you try to use a command and Bash displays the «Command not found» error, it might be because the program is not installed on your system. Correct this by installing a software package containing the command. For example, if you don’t have Nmap installed, then the nmap
command fails when you type it into a terminal:
$ nmap
nmap: command not found
$ sudo dnf install --assumeyes --quiet nmap
$ nmap
Nmap 7.92 ( https://nmap.org )
Usage: nmap [Scan Type(s)] [Options] {target specification}
[...]
[ How well do you know Linux? Take a quiz and get a badge. ]
Stick to the path
The PATH variable is a powerful tool you can use to customize how your system responds to commands, so take some time to get comfortable with it. It’s frequently used when running commands to find the command executable.
In this tutorial, you learned five ways to fix a «Command not found» error in your terminal—three of which rely on the PATH variable. Now that you know what variables are and how command executables are found, you won’t be so mystified when the «Command not found» error appears on your screen.
[ Learning path: Getting started with Red Hat OpenShift Service on AWS (ROSA) ]
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.
sudo apt-get 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.
./GFG.sh
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:
echo $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.
mkdir bin mv Sample.sh bin/Sample.sh
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:
- By appending (This adds our path at the end of the PATH variable)
- 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.
chmod +x Sample.sh
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.
Last Updated :
07 Nov, 2022
Like Article
Save Article
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 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.
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.
Let’s start!
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:
[ec2-user@localhost ~]$ echo $PATH
/home/ec2-user/.local/bin:/home/ec2-user/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin
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):
[ec2-user@localhost]$ ls -al /usr/bin/ch*
-rwxr-xr-x. 1 root root 17488 May 11 2019 /usr/bin/chacl
-rwsr-xr-x. 1 root root 133928 Nov 8 2019 /usr/bin/chage
-rwxr-xr-x. 1 root root 19216 Nov 8 2019 /usr/bin/chattr
-rwxr-xr-x. 1 root root 150528 Apr 9 18:53 /usr/bin/chcon
-rwxr-xr-x. 1 root root 140232 Apr 9 18:53 /usr/bin/chgrp
-rwxr-xr-x. 1 root root 61920 Nov 8 2019 /usr/bin/chmem
-rwxr-xr-x. 1 root root 133952 Apr 9 18:53 /usr/bin/chmod
-rwxr-xr-x. 1 root root 146360 Apr 9 18:53 /usr/bin/chown
-rwxr-xr-x. 1 root root 47816 Nov 8 2019 /usr/bin/chrt
-rwxr-xr-x. 1 root root 14272 May 11 2019 /usr/bin/chvt
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:
[ec2-user@localhost]$ which chmod
/usr/bin/chmod
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.
Makes sense?
Where Is PATH Defined in Linux?
Wondering where is the PATH environment variable defined?
Let’s find out…
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.
In Linux, the dot before the name of a file means that the file is hidden. It’s not visible if we execute the ls command without flags. It’s only visible if you pass the -a flag to the ls command.
The .bashrc file is actually a shell script that gets executed when Linux initialises an interactive shell. This allows you to configure your environment the way you want every time you open your shell.
If I look at the .bashrc file on my system I see the following lines:
# User specific environment
PATH="$HOME/.local/bin:$HOME/bin:$PATH"
export PATH
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.
If you want to add another directory to the PATH you can simply update the .bashrc file.
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:
/home/ec2-user/.local/bin:/home/ec2-user/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin
There’s something that doesn’t make sense to me…
…in the .bashrc file in the home directory on my user I only see:
PATH="$HOME/.local/bin:$HOME/bin:$PATH"
So, where do the following directories come from considering that they are not in my user’s .bashrc file?
/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin
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.
[root@localhost]$ grep -r PATH /etc/* | grep "/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin"
/etc/ssh/sshd_config:# This sshd was compiled with PATH=/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin
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…
The next reason could be that the directory where the command is located is not in the PATH and there could be two reasons for that:
- The command is available on the system but its directory is not in the PATH.
- The command is not available on the system at all.
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.
To update the value of the PATH you have to modify the .bashrc file.
Let’s say the current value of the PATH is:
PATH="$HOME/.local/bin:$HOME/bin:$PATH"
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:
PATH="$HOME/.local/bin:$HOME/bin:$PATH:/opt/install"
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:
PATH="/opt/install:$HOME/.local/bin:$HOME/bin:$PATH"
Notice the dollar $ in front of PATH. This is REALLY important because it refers to the existing value of the variable PATH.
Omitting the $ sign in this line could have catastrophic effects on your system. That’s because the shell wouldn’t know anymore where to find basic commands like ls, cd, vim, etc…
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:
[ec2-user@localhost ~]$ rsync
-bash: rsync: command not found
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:
yum list --installed | grep rsync
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:
rpm -qa | grep rsync
Once again, no results for the rsync package.
So, let’s install it!
The yum search command returns a result for rsync:
[ec2-user@localhost ~]$ yum search rsync
Last metadata expiration check: 1 day, 4:15:26 ago on Sun 19 Jul 2020 05:12:46 PM UTC.
=================================== Name Exactly Matched: rsync ===================================
rsync.x86_64 : A program for synchronizing files over a network
And we can install the rsync package using the “yum install” command:
[ec2-user@localhost ~]$ sudo yum install rsync
......
....
Installed:
rsync-3.1.3-7.el8.x86_64
Complete!
And now if I try to execute the rsync command again to check its version:
[ec2-user@localhost ~]$ rsync --version
rsync version 3.1.3 protocol version 31
Copyright (C) 1996-2018 by Andrew Tridgell, Wayne Davison, and others.
Web site: http://rsync.samba.org/
The command works well!
Conclusion
In this guide we have seen three possible scenarios in which the “command not found” error can occur on Linux when we execute a command:
- We have misspelled the command.
- The command is available on the system but its directory is not in the PATH.
- The command is not available on the system.
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?
Let me know in the comments below! 🙂
I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!
There are various reasons for the Linux shell to throw the «command not found» error. Here’s how to fix it.
If you’re a Linux user, you’ve most likely encountered the “command not found” error on the Linux terminal.
Often when you come across this error, you’ll get a suggestion to install a program, however, there are several potential causes for the «command not found» error.
Understanding Environment Variables and Case Sensitivity
Before we go about fixing common causes of the error, it is important to appreciate a few critical properties of Linux commands.
Unlike Windows, all commands, filenames, and directories on Linux and Unix systems are case-sensitive. This means that all commands and their corresponding arguments or options should appear exactly as they are meant to. Of course, most commands are lowercase.
Environment variables play an important role in Linux. They contain valuable information about your login session and other important details.
When you run a command on Linux, your system will search in your current variables, specifically the PATH variable, to find the command or program that you want to run. If the command is not found, you’ll get an error that it’s not found.
With this understanding, here’s how you can troubleshoot the “command not found” error on Linux.
1. Check for Syntax Errors
You should run all Linux commands exactly as they appear case-wise. For example, the shell treats “ls” and “LS” as different commands on Linux.
Also, if your command contains arguments, make sure you’re using the correct case. The ssh command for port forwarding takes the format:
ssh -fN -L 80:localhost:8080
The “L” and the “N” arguments, in this case, must be uppercase, otherwise, you’ll get an error.
In some cases, the options or arguments may require a preceding hyphen (-) or double hyphen (—), and some arguments may need to be enclosed in quotes or brackets.
Make sure you are using the correct command. Double-check the spelling of the command you are trying to use and ensure that you are using the correct case.
2. Include the Path to Your Executable
Scripts play a vital role in Linux as they allow you to automate mundane tasks. If you write your own Bash program or use some third-party programs, you’ll need to specify the entire path to the program to execute it successfully.
When you download the Open Virtualization Format Tool, for example, you can install it to any directory of your liking. Now, when you try to run the ovftool command from a directory other than the one it was installed in, you’ll get the “command not found” error.
To run the command properly, you need to specify the entire path to the program executable. If, for instance, you’ve installed ovftool in the /opt/ovf directory, then to run ovftool, you’ll have to use the following command:
sudo /opt/ovf/ovftool
Also, pay attention to the slashes. Unlike Windows, which uses backward slashes, Linux uses forward slashes. Use the Tab auto-completion feature of your terminal to avoid typos in directory names.
3. Use Environment Variables
If you find that specifying an entire directory to a command is tiresome, consider adding the program executable to your PATH environment variable.
To add a program executable to PATH, simply run a command in the following format:
PATH = $PATH:/opt/path/to/your/program
For example, to add the Microsoft .NET tools program to your PATH, run the command:
export PATH=$PATH:~/.dotnet/tools
Environment variables are written to the ~/.bashrc file on Bash or the ~/.zshrc file if you’re using the Z shell.
To update and apply the changes you’ve made to the ~/.bashrc file without logging out, run the source command as follows:
source ~/.bashrc
You can check if your program path is successfully added to the PATH variable using the command:
echo $PATH
4. Make Sure That the Program Is Installed
Sometimes, the cause of the “command not found” error could simply be because the program is not even installed in the first place.
If the command you are trying to run is not a built-in shell command, it may be that the program is not installed on your system. In this case, you will need to install the program or the package that contains it.
Depending on your distro, use the default package manager to install the required software. On Debian-based distros, use the apt command, and use DNF or YUM on RHEL-based distros.
5. Use the Correct Privileges
If you are very certain that the program or command you’re trying to run is on your system, and you are using the correct syntax then it could be an issue with the permissions.
Similar to Windows, you’ll need elevated privileges to execute certain programs on Linux. If that’s the case, make sure that you’re using sudo or running the program as the root user.
Make Use of Environment Variables on Linux
Ensure you use the correct syntax when executing Linux commands and consider adding the programs that you often run to your environment variables.
Environment variables play such an important role in Linux that understanding them is key for your day-to-day use of the operating system.
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.
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 …
ls -l foo.sh
… 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.
$ ls -l foo.sh # Check file permissions of foo
-rw-r--r-- 1 rkielty users 0 2012-10-21 14:47 foo.sh
^^^
^^^ | ^^^ ^^^^^^^ ^^^^^
| | | | |
Owner| World | |
| | Name of
Group | Group
Name of
Owner
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)
$ chmod +x foo.sh # The owner can set the executable permission on foo.sh
$ ls -l foo.sh # Now we see an x after the rw
-rwxr-xr-x 1 rkielty users 0 2012-10-21 14:47 foo.sh
^ ^ ^
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
env | grep ^PATH
Here’s some sample output of running the above env
command first as an ordinary user and then as the root user using sudo
rkielty@rkielty-laptop:~$ env | grep ^PATH
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
rkielty@rkielty-laptop:~$ sudo env | grep ^PATH
[sudo] password for rkielty:
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/X11R6/bin
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.
The directory where foo.sh
resides is not present in the PATH variable of the root user, hence the command not found error.
Apt-get — это пакетный менеджер, который используется по умолчанию в семействе дистрибутивов Debian и Ubuntu. Учитывая, что это пакетный менеджер, один из почти самых основных пакетов системы, то логично, что программа должна присутствовать в каждом дистрибутиве. Но все же некоторые пользователи встречаются с ошибкой apt get command not found.
В этой статье мы рассмотрим почему возникает такая ошибка, как это вообще может быть и как исправить 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:
echo $PATH
Вы должны увидеть в ней ссылку на /usr/bin. Если такой строчки нет, то проблема была здесь, а строчку нужно добавить в конец:
export PATH=текущее_содержимое:/usr/bin
Например:
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/snap/bin
Если вы вносили изменения в файл /etc/profile, и переменная PATH сломалась из-за этого, то нужно внести исправления и в этот файл.
Последний вариант, если ничего не помогло, это переустановить утилиту. Мы просто скачаем ее из официального сайта и установим в систему. Только нужно выбирать версию для своей операционной системы. Вы можете скачать пакет с помощью браузера или таких команд:
Для Ubuntu Xenial:
wget http://security.ubuntu.com/ubuntu/pool/main/a/apt/apt_1.2.15ubuntu0.2_i386.deb
Для Ubuntu Yakkety:
wget http://security.ubuntu.com/ubuntu/pool/main/a/apt/apt_1.3.3_i386.deb
Теперь осталось установить загруженный пакет:
sudo dpkg -i apt*
Готово, после этого ошибка apt get command not found должна исчезнуть и вы сможете нормально работать со своими пакетами.
Выводы
В этой статье мы рассмотрели почему не работает apt get, из-за чего возникает ошибка apt get команда не найдена, а также как ее решить. Надеюсь, приведенная здесь информация была полезной для вас.
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .
Об авторе
Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.