There are many scenarios when you get «sudo command not found error» and you keep looking for solutions on the internet to fix it. One of the common examples, when you have installed Debian with a minimal package and trying to run sudo. For me whenever I try to ssh into any of the remote servers and run sudo, I get this «bash: sudo commands not found error». So I decided to write a post, which covers all the scenarios of this famous error.
Below mentioned errors will be covered in this post. so if you are getting any of the following errors, this post will definitely solve your error —
- sudo command not found mac
- sudo command not found ubuntu
- sudo command not found debian
- zsh sudo command not found
- sudo command not found windows
- sudo command not found centos
- bash: /usr/bin/sudo: No such file or directory
These are the common scenarios that result in this error —
- You have installed a linux distribution with minimal package like Debian
- Sudo is not installed
- Path is not setup for sudo command
- You are trying to ssh a remote server first time and sudo is not working
Before getting into the solutions, if you are a newbie let’s understand why sudo is used?
Table of Contents
- 1 Why sudo is used in Linux before every command?
- 2 How to fix sudo command not found error in Debian/Ubuntu like Distros
- 3 Solution-1 Check and install sudo package
- 4 Solution2 — Setup path variable to fix sudo command not found errors
- 5 Fix «sudo command not found error» in Fedora/AlmaLinux/Rocky Linux Distros
- 6 Solution3- Install sudo and add user to «Wheel» group to fix sudo errors
- 7 Frequently asked questions on sudo
- 8 Ending Note
Why sudo is used in Linux before every command?
Sudo is one of the famous prefixes to any command you run in the Linux world. It allows running any Linux command with elevated privileges to run administrative tasks. Also, the operations which are only permitted by a root user can be done using a normal user with sudo rights. The «sudoers» file controls, who can use the sudo command to gain elevated access and location is /etc/sudoers in all Linux distributions.
How to fix sudo command not found error in Debian/Ubuntu like Distros
As we discussed already, there may be many reasons to encounter this error. As you will see in the image, running the «sudo ifconfig -a» command results in «bash: /usr/bin/sudo: No such file or directory error«. I am running this command in Ubuntu 21.04 installed as VM.
Let’s deep dive and find the fixes for different scenarios —
Solution-1 Check and install sudo package
This is very uncommon when sudo is not installed by default with Linux installation. Still, you may get this situation when you have installed the Debian Linux with the minimal package. Follow these steps to fix it —
Step1.1 List installed packages in Ubuntu and look for the «sudo» package
$ apt list --installed | grep -i sudo
If you can find package name sudo with «installed» status as shown in the image. Then you can directly move to solution-2 to fix the «sudo: command not found error«.
If you don’t have the sudo package installed, run the following command to install it in Ubuntu or Debian based distros. You would need root access to achieve this.
Step1.2 Switch to root user
$ su root
Enter «root» password, when prompted.
If you don’t have a root password, then follow this link to reset your root password.
Step1.3 Run apt command to install sudo package in Ubuntu/Debian
# apt install sudo
Refer to the following image for reference.
Step1.4 Give sudo rights to your own user by adding it to the sudo group
# usermod -aG sudo yourusername
For example, I will add my user «dev» to sudo group —
# usermode -aG sudo dev
Step1.5 Verify your user is added to the sudo group
Open /etc/passwd file and check whether your user is added to the sudo group or not.
# cat /etc/group | grep -i username
I will check for my user «dev» in this example.
# more /etc/group | grep -i username
Step1.6 Make sure your sudoers file have sudo group added
- Run
visudo
command to modify sudoers file and add the following line into it (if it is missing):
# Allow members of group sudo to execute any command
%sudo ALL=(ALL:ALL) ALL
Press Ctrl + X and press «Y» to save the file and exit from the nano editor.
Exit from the root shell and check the sudo command functionality.
- Run sudo -h command. Now you will not get any «sudo command not found error» as it’s fixed now.
Solution2 — Setup path variable to fix sudo command not found errors
If you have a sudo package installed as explained in Step 1.1 and still you are getting sudo command not found error. It means you don’t have «/usr/bin/» setup in the PATH variable or your /etc/environment file got messed up.
To add sudo in your Path variable, add /usr/bin/ directory by following the method.
Step2.1 Switch to root user
$ su root
Enter root user password, when asked.
Step2.2 Run /usr/bin/sudo
command to check whether it’s working or not
# /usr/bin/sudo -h
Step2.3 Edit /etc/environment
file and add «/usr/bin"
directory in PATH
# vi /etc/environment
Alternatively, you can also run export command to set up the path variable
export PATH=$PATH:/usr/bin
In case you are getting visudo and usermod command not found errors also. Make sure you add /usr/sbin in the PATH variable as shown in the last step.
Fix «sudo command not found error» in Fedora/AlmaLinux/Rocky Linux Distros
This section covers sudo error for all the Linux distros based on RedHat like Fedora, AlmaLinux, CentOS and Rocky Linux. I have Rocky Linux Installed as a virtual machine. The procedure is the same as explained earlier, Look for the package, install it and set the path variable, if required. But the commands will differ now.
Solution3- Install sudo and add user to «Wheel» group to fix sudo errors
You have the option to set up sudo during installation in RedHat based Linux distros. But if you forgot to do that, You must have access to the root user to set up sudo for your user.
Step3.1 — Login with root user and check for sudo package installation
Follow this link to reset your root password, in case you forgot or don’t have it.
Once you are done with login as root, open Terminal and type
# yum list installed | grep -i sudo
If you get the sudo package installed already skip to the next step3.3.
Step3.2 Install sudo package
You can use the «yum» or «dnf» command to install any package from the repository.
Update all old packages and refresh the repository.
# dnf update
Then install the sudo package using the dnf
or yum
command.
# yum install sudo or # dnf install sudo
Step3.3 Add user to the wheel
group
The wheel group is already set to provide sudo access to run all commands. So is the quickest way is to add your user to this group. Switch to the root user first using su
command
su -
Now run usermod
command to add your user in the
wheel group.
# usermod -a -G wheel "username"
For example, I will add my user «dev» as an example
# usermod -a -G wheel "dev"
Step4.4 Check with the id
command
Next, run the id command to see whether your user is part of the wheel group or not.
# id "username"
Example: My user dev is part of 10(wheel) the
group.
# id dev
Congrats! you must have fixed your «sudo command not found error » now and you can run all your privileged commands using sudo.
Frequently asked questions on sudo
Q1: Why is sudo not working?
These are many reasons when sudo may not work —
1. You don’t have a sudo package installed
2. If the sudo package is installed then the path variable is not set up correctly
3. Your system got broken and all your packages and permissions got messed up
4. Your user is not added to the sudo or wheel group based on your Linux distro.
Q2: How do I enable sudo?
If the sudo package is already installed based on your Linux distro run the following command. Replace «dev» with your username.
for Ubuntu and Debian based distros —
$ su root
Then run the usermod command to add your user to the sudo group
# usermode -aG sudo dev
For RedHat based distros —
Switch to root (superuser)
$ su -
Add to the wheel group.
# usermod -a -G wheel dev
Q3: How do I find sudo commands?
Open terminal and type sudo -h
. It will show you all the sudo command options and arguments. You can also type man sudo
to get the manual of the sudo command.
Q4: How do I fix sudo command not found Mac?
Run the following sequence of commands to fix the sudo command not found error in macOS.
1. Check the syntax of command and spelling of sudo, so that you are sure, you are not running the misspelt command
2. switch to root user$ su -
3. Run the following command
In the case of OS prior to Catalina
# visudo /etc/sudoers
in the case of Catalina
# visudo /private/etc/sudoers
4. Add your user as follows in sudoers file —
username ALL=(ALL) ALL
replace username with your user. e.g John
Save and exit sudoers file
5. reopen the terminal and it will fix all your zsh: sudo command not found error in macOS.
Q5: Do I need to install sudo?
By default all the Linux or Unix distros have sudo installed. But in case you don’t, then you must install sudo. it is the recommended way to use root privileged commands (only when required) and helps to avoid mistakes that can break your system.
Ending Note
I have covered all the possible solutions to fix the sudo command not found error and I hope this tutorial is helpful to you. In case, none of the solutions works for you and your system has broken severly, Either re-install your system or let me know the issue via your comments.
I will try to help you to the best of my knowledge.
Keep Learning!!
I have an up and running containers and I wish to execute a database backup. Apparently, a simple command from the docker such as: sudo mkdir new_folder
result in: bash: sudo: command not found
What have I tried (on an intuitive level) I accessed one of the running container with docker exec -i -t 434a38fedd69/bin/bash
and RUN
apt-get update
apt-get install sudo
when exit back to docker and tried to perform sudo mkdir new_folder
but I got the same message bash: sudo: command not found
Baresp@adhg MINGW64 /c/Program Files/Docker Toolbox/postgre
$ mkdir new_folder
mkdir: cannot create directory ‘new_folder’: Permission denied
Baresp@adhg MINGW64 /c/Program Files/Docker Toolbox/postgre
$ sudo mkdir new_folder
bash: sudo: command not found
BTW, I’m not sure if this is relevant but the docker-compose file I was using is:
version: '2'
services:
postgres:
image: postgres
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: changeme
PGDATA: /data/postgres
volumes:
- /data/postgres:/data/postgres
ports:
- "5432:5432"
networks:
- postgres
restart: unless-stopped
container_name: xx_postgres
pgadmin:
links:
- postgres:postgres
image: fenglc/pgadmin4
volumes:
- /data/pgadmin:/root/.pgadmin
ports:
- "5050:5050"
networks:
- postgres
restart: unless-stopped
container_name: xx_pgadmin
networks:
postgres:
driver: bridge
asked Aug 7, 2018 at 19:59
adhgadhg
10.2k11 gold badges56 silver badges94 bronze badges
1
First, nothing you do in a docker exec
is persistent outside of that particular running container (copy of the image), so if you want future containers run from that image to include sudo
, those apt-get
commands need to go into the Dockerfile that builds the image. Which, since you’re using docker-compose
, would require you to first make a Dockerfile and specify its location in the YAML.
Second, what do you mean «exit back to docker»? Nothing you do inside a container is going to have any effect on the system that Docker itself is running on, but it looks like you’re running software install commands inside a Docker container and then expecting that to result in the newly-installed software being available outside the container on the Windows system that is running Docker.
answered Aug 7, 2018 at 20:02
Mark ReedMark Reed
89.6k15 gold badges135 silver badges167 bronze badges
2
To do a backup of the postgres database in the container, you first have to enter the container (similar to how you do it):
docker exec -it postgres bash
(substitude postgres with the real container name you get from docker-compose ps
)
Now you are in the container as root. That means, you don’t need sudo for anything. Next create your backup folder:
mkdir /tmp/backup
Now run the backup command, from a quick Google I found the following (you might know better):
pg_dumpall > /tmp/backup/filename
Then exit the shell within the container by typing exit. From your host system run the following to copy the backup file out of the container:
docker cp postgres:/tmp/backup/filename .
(postgres is your container name again)
answered Aug 8, 2018 at 10:19
AlwiniusAlwinius
1,9161 gold badge9 silver badges12 bronze badges
1
-bash: sudo: command not found
You are using a kali version prior to 2020.1 , sudo
isn’t installed by default. To install it:
# apt install sudo
-bash: git: command not found
git
isn’t installed by default, to install it:
# apt install git
Starting from kali 2020.1 root access has been dropped, users must use sudo
.
To Enable/Disable password-less privilege escalation on kali-linux you need to install the kali-grant-root
package :
$ sudo apt install kali-grant-root
$ sudo dpkg-reconfigure kali-grant-root
With 2020.1 Kali has swapped to a privileged non-root user by default. This means that root has no password set, and the account created during installation is the one to use. It is possible to re-enable access to the root user, however this is not recommended.
Sudo on Kali
Because Kali creates a user with administrative privileges by default, users can use sudo right away and supply their password for authentication. Should a user wish to enable password-less sudo, which poses a security risk should someone gain access the the user account, they have that option.
sudo apt install -y kali-grant-root && sudo dpkg-reconfigure kali-grant-root
The previous command installs a package that will allow for a user to be added to a trusted group that will not need to supply a password when using
sudo
. This does not mean however that root will be reinstated.
Kali linux docs:
- All about sudo
I want to install a game in Windows using Cygwin. When trying to use the sudo
command, I receive the following error:
-bash:sudo:command not found
I get a similar error when trying to use command add-apt-repository
:
unable to start "add-apt-repository" this specified file was not found
Why are these commands not recognized?
LawrenceC
71.9k15 gold badges123 silver badges211 bronze badges
asked Apr 4, 2016 at 14:11
3
You may have misunderstood what Cygwin is useful for. From their website:
Cygwin is not: a way to run native Linux apps on Windows. You must rebuild your application from source if you want it to run on Windows.
Packages like sudo
do not exist in Cygwin. You can find available packages here.
They also have a detailed FAQ that plainly describes what it is, how it can be used, and so on.
answered Apr 4, 2016 at 15:14
rootroot
3,5327 gold badges27 silver badges45 bronze badges
I think I tried steps below after doing some research & succeeded (on Windows)
-
Install scoop using powershell 3
iex (new-object net.webclient).downloadstring('https://get.scoop.sh')
-
Do
scoop install --global sudo
- Make sure paths (
C:Users<username>scoopshims
&C:ProgramDatascoopshims
) added in environmental path variable.
Vylix
1,7033 gold badges21 silver badges26 bronze badges
answered Jul 9, 2017 at 11:57
1
На чтение 3 мин. Опубликовано 15.12.2019
Если в ОС Debian или Ubuntu вы захотели выполнить любую команду с sudo и получили ошибку
-bash: sudo: command not found
То скорее всего у вас просто не установлен sudo
Чтобы исправить эту проблему заходим под суперпользователем, для этого вводим команду
вводим пароль от рута (root)
И уже с root-правами выполняем команду
После этого все должно заработать
ВАЖНО: Чтобы текущий пользователь мог выполнять команды с правами суперпользователя используя sudo — он должен состоять в соответствующей группе,
Чтобы добавить пользователя в группу sudo, выполните команду
где user — имя вашего пользователя
Если вы установили Linux в конфигурации minimal — то очень вероятно что при попытке выполнить команду от администраторсикх прав вы увидите сообщение -bash: sudo: command not found. Это не значит что вы неправильно выдали sudo-права. Скорее всего в минимальной конфигурации вашего дистрибутива отсутствует утилита sudo.
Если у вас Ubuntu/Debian — выполняем из-под root команду:
[docekr newbie here] I have an up and running containers and I wish to execute a database backup. Apparently, a simple command from the docker such as: sudo mkdir new_folder result in: bash: sudo: command not found
What have I tried (on an intuitive level) I accessed one of the running container with docker exec -i -t 434a38fedd69/bin/bash and RUN
when exit back to docker and tried to perform sudo mkdir new_folder but I got the same message bash: sudo: command not found
BTW, I’m not sure if this is relevant but the docker-compose file I was using is:
2 Answers 2
First, nothing you do in a docker exec is persistent outside of that particular running container (copy of the image), so if you want future containers run from that image to include sudo , those apt-get commands need to go into the Dockerfile that builds the image. Which, since you’re using docker-compose , would require you to first make a Dockerfile and specify its location in the YAML.
Second, what do you mean «exit back to docker»? Nothing you do inside a container is going to have any effect on the system that Docker itself is running on, but it looks like you’re running software install commands inside a Docker container and then expecting that to result in the newly-installed software being available outside the container on the Windows system that is running Docker.
To do a backup of the postgres database in the container, you first have to enter the container (similar to how you do it):
(substitude postgres with the real container name you get from docker-compose ps ) Now you are in the container as root. That means, you don’t need sudo for anything. Next create your backup folder:
Now run the backup command, from a quick Google I found the following (you might know better):
Then exit the shell within the container by typing exit. From your host system run the following to copy the backup file out of the container:
03 Feb, 22
by Susith Nonis
4 min Read
List of content you will read in this article:
- 1. What is the Sudo command?
- 2. What is a root user?
- 3. Fixing Sudo command not found errors
- 4. Conclusion
In Linux and UNIX-like systems, the Sudo command executes a specific command with root privileges. The user who runs this command has complete access to the system and can modify or add anything.
If you are an experienced Linux user, you might have encountered the “sudo: command not found” error while setting up the Linux desktop or virtual machine. Though you may have the command installed, you may get this error message in rare cases. However, this error message can be intimidating and prevents you from proceeding further with the setup process. As a result, it becomes obligatory to fix this error message.
Fortunately, we have a simple solution to this problem. Let us explore the solution in this article. But before it, let us have a brief introduction to the Sudo command.
What is the Sudo command?
Sudo stands for “Super User Do” and is pronounced as “sue dough.” It is a command-line utility that is usually built-in for UNIX and Linux-based operating systems and grants users permission to execute different commands at the most potent level of the system, the root level. It is generally used as a prefix for many other Linux commands, and only superusers have permission to execute them.
This command is equivalent to the “Run as Administrator” in Windows. Sudo also keeps a log of all commands and arguments.
What is a root user?
As there are several user accounts on the Linux system, many of them are assigned a set of privileges that do not have the right permissions to carry out administrative tasks. Also, users with limited privileges are not granted permission to access certain filesystem areas.
However, one user has the right to access any part or area of the system called the root user. The root user is the name given to a Linux user who can perform any operation on the machine without requiring permission from another user. The root user is also known as the Super User. This user’s user ID is 0.
It’s more powerful than Administrator in Windows, more akin to SYSTEM in Windows, and you can log into the system. The root user is in charge of creating new users and assigning various permissions on the machine. The command that must be run as a root user begins with Sudo.
Fixing Sudo command not found errors
Being a command, sudo is also a package that comes installed by default on the Linus systems. However, certain Linux distributions do not get sudo installed, and when you run the command on such systems, you receive the error message “sudo: command not found.”
Here is a solution that you can follow to fix the error:
- Switch to the root user
- Type in the following command to go to the root user mode
$ su -
- Update the repositories using the following command
$ apt update
- Run the following command on Debian-based distributions:
$ apt-get install sudo
- The output will be something like this:
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
sudo
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 0 B/1,059 kB of archives.
After this operation, 4,699 kB of additional disk space will be used.
Get:1 http://security.debian.org/ squeeze/updates/main sudo amd64 1.7.4p4-2.squeeze.3 [610 kB]
Fetched 610 kB in 4s (132 kB/s)
Selecting previously unselected package sudo.
(Reading database ... 135532 files and directories currently installed.)
Unpacking sudo (from .../sudo_1.7.4p4-2.squeeze.3_amd64.deb) ...
Processing triggers for man-db ...
- Run the following command on RHEL/CentOS/Fedora:
$ yum install sudo
- Give all the sudo permissions using the following command
$ user od -AG <username>
- Open the ‘sudoers’ file to check the permissions
$ nano /etc/sudoers
- Check if the sudo has all the permissions associated.
# Full access for members of the sudo group
%sudo ALL=(ALL:ALL) ALL
# User privilege specification
root ALL=(ALL:ALL) ALL
- You should now be able to run all the commands using sudo.
Conclusion
For security purposes, the Linux systems provide permissions only to the root user and the users allowed by the root user to perform administrative tasks. We hope the above solution will help you fix the error “sudo: command not found” on most Linux distributions.
Good Luck!
People also read:
- How to Create Sudo User in Debian
- How to use Sudo on Debian, FreeBSD, and CentOS
Главная » Linux » Debian » Как исправить ошибку Sudo Command Not Found в Debian VPS
Опубликовано 06.07.2022
В этой статье мы покажем вам, как исправить ошибку sudo command not found в Debian 10 VPS.
Sudo — это программа для Unix-подобных компьютерных операционных систем. Команда sudo позволяет пользователям запускать программы с привилегиями суперпользователя. Она может означать «superuser do«, так как изначально это все, что она делала, однако сейчас она может означать «substitute user, do«, потому что sudo может выполнять команды и от имени других пользователей.
После установки Debian 10 вы не можете выполнить задачи с привилегиями, запустив команду sudo. И вы получите ошибку «sudo command not found in Debian 10«.
Исправление ошибки Sudo Command Not Found в Debian
Войдите на сервер Debian 10 под пользователем root.
После входа в систему выполните следующую команду, чтобы проверить ошибку sudo:
sudo apt update
Вы получите следующую ошибку:
-bash: sudo: command not found
По умолчанию пакет sudo находится в репозитории Debian 10 по умолчанию. Вы можете установить его с помощью команды apt, как показано ниже:
apt install sudo -y
После установки пакета Sudo вам нужно будет создать нового обычного пользователя и добавить его в группу sudo.
Сначала создайте нового пользователя с помощью следующей команды:
adduser sajid
Теперь добавьте только что созданного пользователя в группу sudo:
usermod -aG sudo sajid
Эта команда предоставит привилегии sudo пользователю sajid и позволит ему использовать команду sudo для выполнения административных привилегий.
Вы также можете проверить, был ли пользователь добавлен в группу sudo, используя следующую команду:
id sajid
Далее вы должны увидеть, что пользователь user1 принадлежит к двум группам: sajid и sudo.
uid=1002(sajid) gid=1002(sajid) groups=1002(sajid),27(sudo)
Теперь переключите пользователя на user1 и выполните любую команду с помощью sudo:
su - sajid
sudo apt update
Заключение
Поздравляем!!!
Итак, вы теперь можете исправить ошибку sudo command not found на виртуальном частном сервере (VPS) в Debian 10. Наслаждайтесь.