Reputation: 17825
I'm writing a shell script to start a few processes for me. Because those processes need sudo access, I run my shell script with sudo. However, I don't have access to my path variables when I do that. I've added a shell script to /etc/profile.d/extra-path.sh that adds those for my user.
Could someone tell me the way I should add those path variables so they can be accessed in the shell script run with sudo, or is there a way to run the commands with my user path in the shell script itself?
Here's the script I'd like to have work:
#!/bin/bash
#start stuff up
nohup mongod
#mongod fails as an unknown command, even though it's part of my path
nohup /cust/env/local/cust/jboss-5.1.0.GA/bin/run.sh -b 0.0.0.0 -Djava.awt.headless=true
#jboss needs access to the JAVA_HOME path variable which
#doesn't exist on the path used in this shell script
Upvotes: 1
Views: 3907
Reputation: 6451
Try this..
sudo -i /path/to/script.sh
or..
sudo env PATH=$PATH /path/to/script.sh
or..
sudo -E /path/to/script.sh
One of them should work, depending on your system.
Upvotes: 6
Reputation: 13065
The fact that sudos drops the path is a feature. Don't try to work around it by copying the path from the user as some of the examples show. (Imagine if a bad user copies bash into /tmp/ls, then sets PATH=/tmp/. The root shell might do ls
and accidentally run the bash command with root privileges! Oops, the bad user now has a root shell.)
You could add the extra path by adding this to the top of your script (just under #!/bin/sh
)
. /etc/profile.d/extra-path.sh
(The . means "read this file as if it was copied here")
Upvotes: 2
Reputation: 17825
There are a few different solutions to this I've found out.
sudo -i [command]
and
sudo -s [command]
both work, but with -i you access the command as if you're in the root directory, so you have to specify the full path to the shell script (or put it in your bin). With -s you access the command as if you're in your current directory.
You can also use these either to run the myscript.sh
script itself, or use them inside the script in front of the commands you need the sudo access for. I preferred to put them in front of those commands as that way I don't have to type out as much to run my script!
Upvotes: 1