The other solutions I've seen here so far are based on some system definitions, but it's in fact possible to have sudo
use the current PATH
(with the env
command) and/or the rest of the environment (with the -E
option) just by invoking it right:
sudo -E env "PATH=$PATH" <command> [arguments]
In fact, one can make an alias out of it:
alias mysudo='sudo -E env "PATH=$PATH"'
(It's also possible to name the alias itself sudo
, replacing the original sudo
.)
It seems that linux will say "command not found" even if you explicitly give the path to the file.
[veeam@jsandbox ~]$ sudo /tmp/uid.sh;echo $?
sudo: /tmp/uid.sh: command not found
1
[veeam@jsandbox ~]$ chmod +x /tmp/uid.sh
[veeam@jsandbox ~]$ sudo /tmp/uid.sh;echo $?
0
It's a somewhat misleading error, however it's probably technically correct. A file is not a command until its executable, and so cannot be found.
Try chmod u+x foo.sh
instead of chmod +x foo.sh
if you have trouble with the guides above. This worked for me when the other solutions did not.
Ok this is my solution: in ~/.bash_aliases just add the following:
# ADDS MY PATH WHEN SET AS ROOT
if [ $(id -u) = "0" ]; then
export PATH=$PATH:/home/your_user/bin
fi
Voila! Now you can execute your own scripts with sudo or set as ROOT without having to do an export PATH=$PATH:/home/your_user/bin everytime.
Notice that I need to be explicit when adding my PATH since HOME for superuser is /root
You can also create a soft link to your script in one of the directories (/usr/local/bin
for example) in the super user PATH. It'll then be available to the sudo.
chmod +x foo.sh
sudo ln -s path-to-foo.sh /usr/local/bin/foo
Have a look at this answer to have an idea of which directory to put soft link in.
Check for secure_path on sudo
[root@host ~]# sudo -V | grep 'Value to override'
Value to override user's $PATH with: /sbin:/bin:/usr/sbin:/usr/bin
If $PATH
is being overridden use visudo
and edit /etc/sudoers
Defaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin
chmod +x foo.sh
#!/bin/sh
or some such.sudo pwd
sudo
command not found
to check whether the sudo package is installed on your system, type sudo
, and press Enter . If you have sudo
installed the system will display a short help message, otherwise you will see something like sudo: command not found
To install sudo, run one of the following commands using root account:
apt-get install sudo
# If your system based on apt package manager
yum install sudo
# If your system based on yum package manager
Source: Stackoverflow.com