Problems with sudo in path

Using:

Linux nomemory 2.6.32-24-generic #43-Ubuntu SMP Thu Sep 16 14:17:33 UTC 2010 i686 GNU/Linux

I have a folder in my $HOME called ~/.scriptfarm/scripts where i keep some of my custom scripts.

nomemory@nomemory:~$ ls -l /home/nomemory/.scriptfarm/script
total 20
-rwxr-xr-x 1 nomemory nomemory 10 2010-09-21 01:31 aaa
-rwxr-xr-x 1 nomemory nomemory 31 2010-09-21 00:47 pt.chc
-rwxr-xr-x 1 nomemory nomemory 35 2010-09-21 00:47 pt.int
-rwxr-xr-x 1 nomemory nomemory 34 2010-09-21 00:47 pt.rem
-rwxr-xr-x 1 nomemory nomemory 54 2010-09-21 00:47 pt.up

The problem is that in Ubuntu none of the scripts are working when prefixed with sudo. The behavior is different on Arch, where the scripts are working.

Let me give you an example (aaa is a foobar-type script):

nomemory@nomemory:~$ aaa
aaa
nomemory@nomemory:~$ sudo aaa
sudo: aaa: command not found
nomemory@nomemory:~$

And if a echo $PATH:

nomemory@nomemory:~$ sudo echo $PATH
/home/nomemory/.scriptfarm/script:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

Do you know why my scripts don't work if I prefix them with sudo. Any solutions ?

Later edit: The work-around I found was to add an alias for sudo: sudo env PATH=$PATH $@ .


Your test is misleading, because PATH is expanded before calling sudo. Instead, do:

sudo sh -c 'echo $PATH'

and you will see that there is a different path.

To include /home/nomemory/.scriptfarm/scripts in your system-wide PATH, you can modify /etc/profile:

PATH="$PATH:/home/nomemory/.scriptfarm/scripts"

In Ubuntu (10.04 at least) there is an option in the sudoers file to reset the environment.

Defaults    env_reset

You can remove it or you should be able to use SETENV on a per-user basis to keep the old environment.

The man page says about env_reset:

If set, sudo will reset the environment to only contain the LOGNAME, SHELL, USER, USERNAME and the SUDO_* variables. Any variables in the caller's environment that match the env_keep and env_check lists are then added. The default contents of the env_keep and env_check lists are displayed when sudo is run by root with the -V option. If the secure_path option is set, its value will be used for the PATH environment variable. This flag is on by default.


It looks like the problem is that Ubuntu compiles sudo with the SECURE_PATH option, thus making it impossible to pass your PATH environment. You can see this by specifying the -V option when running as root. Thus the command sudo sudo -V dumps a list of defaults. It appears the only workaround is to recompile sudo.


You could use which aaa to find out where aaa is located, then run it from there. Failing that, you may be able to

 sudo 'export PATH='$PATH'; aaa'

Substitute nomemory for the name of your user account those files are located in:

sudo ~nomemory/.scriptfarm/scripts/aaa

Absolute paths = ♥