I’m using Ubuntu 14.04. I’m having trouble getting a command picked up in my $PATH using sudo. I have added this to my /root/.profile file

# ~/.profile: executed by Bourne-compatible login shells.

if [ "$BASH" ]; then
  if [ -f ~/.bashrc ]; then
    . ~/.bashrc

export PATH=$PATH:/usr/local/rvm/rubies/default/bin

mesg n

I have logged out and logged back in as my user with sudo privileges. Then I try and run the command within the $PATH but I get a “command not found” …

daveuser@mymachine:/home/rails/myproject$ sudo gem pristine --all
sudo: gem: command not found
daveuser@mymachine:/home/rails/myproject$ sudo echo $PATH
/usr/local/rvm/gems/ruby-2.3.0/bin:/usr/local/rvm/gems/ruby-2.3.0@global/bin:/usr/local/rvm/rubies/ruby-2.3.0/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/    bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/local/rvm/bin
daveuser@mymachine:/home/rails/myproject$ sudo which gem
daveuser@mymachine:/home/rails/myproject$ which gem

Notice that when I echo $PATH I get exactly the PATH where the “gem” command lives. What else do I need to do to get my “gem” command recognized when I run the command as the sudo user?

Edit: The preserve-env didn’t work. here’s what happened …

remoteuser@remotemachine:/home/rails/myproject$ sudo --preserve-env gem pristine --all
[sudo] password for remoteuser: 
sudo: gem: command not found

Edit 2: output of sudo -l

remoteuser@rtemotemachine:/home/rails/myproject$ sudo -l
Matching Defaults entries for remoteuser on rtemotemachine:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin

User remoteuser may run the following commands on rtemotemachine:
    (ALL : ALL) ALL

By Default sudo resets environment variables for security reasons, check for following line in /etc/sudoers

Defaults    env_reset

PATH variable is reset to "secure_path" value .

e.g. Defaults    secure_path = /sbin:/bin:/usr/sbin:/usr/bin

You can try

sudo env "PATH=$PATH" [command] to preserve path of sudo -E didn't work.

A better explanation can be found here



sudo --preserve-env

-E, --preserve-env Indicates to the security policy that the user wishes to preserve their existing environment variables. The security policy may return an error if the user does not have permission to preserve the environment.

  • I still got a command not found when I ran that. I included teh output in my question. – Dave Oct 22 '16 at 17:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.