bash profile works for user but not sudo

Solution 1:

When you run the script as sudo you are trying to access root. So your $HOME/.profile wont be accessed instead /root/.profile will be accessed.

So make the changes what ever you did in $HOME/.profile to /root/.profile. To create /root/.profile. Use the following commands.

sudo su
cd /root
touch .profile

after making the changes try running the script.

or edit $HOME/.bashrc and add the following line

alias sudo='sudo env PATH=$PATH $@'

Hope this helps.

Solution 2:

You can preserve the value of $PATH when using sudo. Use visudo to add $PATH to the list of variables to keep. A line like the following in /etc/sudoers should do the trick:

Defaults env_keep += "PATH"

Solution 3:

that is the behavior of sudo in ubuntu..

for example run following command

echo 'echo $PATH' | sh

and than this one

echo 'echo $PATH' | sudo sh 

you see the output is different! to avoid different paths put the following in your ~/.bashrc

alias sudo='sudo env PATH=$PATH'