I have a bash script which runs commands that require root privileges. I'm trying to decide between setting "su root" at the start of the script, or running each command prefixed with "sudo". What are the pros and cons of these methods, and which is more secure? Or is there a better method to use? Thanks!
3 Answers
sudo
is better for security. If you have any vulnerabilities in your script, then those can be exploited if you are running as root. By using sudo
, your are limiting your holes only to the scripts you call. So, assuming the scripts you call are secure, then using sudo
in your script will be secure as well.

- 2,041
- 1
- 14
- 20
-
that's a good point, thanks – Nathan Aug 13 '13 at 18:29
-
Don't forget to accept the answer if you think your question is done. – Trenin Aug 13 '13 at 18:30
-
I was waiting to see more opinions/responses – Nathan Aug 13 '13 at 18:32
The best and safest method to use is to actually call the script with sudo. eg. sudo scriptName
. Putting su root
or sudo commandInScript
are essentially doing the same thing. Calling for root access in the script. Rather than having the script run as root when you call the script.

- 9,534
- 2
- 23
- 35
I agree with trenin that sudo would be the best way to do it.But it might be annoying to type sudo in front of every command. You may as well
do stuff
change to root
do super user stuff
change back to regular user
Also if you are running a script as root, having part of it failing may cause unexpected behaviour. I would recommend adding the 'set -e' flag since bash will exit immediately if any command exits with non-zero. You may undo this effect with 'set +e'.
Another way would be, run your whole script as root (su) but allow access to it only to certain user as described here by DaveParillo
Hope it helped