Reputation: 126445
Which pattern is preferable:
#!/bin/bash
echo Installing blah
apt-get install -y blah
...which will fail if run without root perms, or:
#!/bin/bash
echo Installing blah
sudo apt-get install -y blah
...which will succeed as long as the user has sudo access.
I have tended to use the second pattern, but it seems to be rare, so I'm asking what its disadvantages are. The benefits I see are:
I guess downsides include that the use of root permissions might be surprising ("I didn't type sudo
, so I didn't expect anything like apt-get to be run...."). What else?
Upvotes: 6
Views: 1733
Reputation: 531758
The second option is the correct option. Commands that don't require root access should not be run as root just to simplify your script. Commands that do require root access (or access by any specific user, for that matter) should be run by sudo. For clarity, you can use the -p
option to sudo
to present a custom prompt which can explain exactly why the user is asked for their password.
Option two is also preferable because sudo
is highly configurable, and the user may already have permission to run specific commands with sudo
without a password, so it's possible the user would not be inconvenienced by a password prompt. It's less likely that the user is allowed to sudo
arbitrary commands (such as your script) without a password.
Upvotes: 2
Reputation: 201467
You could always test if the user is root (id -u
gets the uid of the current user, and 0 is root), and run sudo
if they aren't -
#!/bin/bash
echo Installing blah
CMD=""
if [ "$(id -u)" != "0" ]; then
CMD="sudo"
fi
${CMD} apt-get install -y blah
The more common approach would be to exit with an error condition if they aren't root,
#!/bin/bash
if [ "$(id -u)" != "0" ]; then
echo "sudo $0 (must run as root)"
exit 1
fi
echo Installing blah
apt-get install -y blah
Upvotes: 2
Reputation: 555
I will prefer second Pattern, because running few commands with sudo is better rather then running entire script with root permissions in which some commands are needless to have root access and so if you perform these commands with root user further using that command outputs will again need root access or you will have to change the ownership. So I will prefer second approach where sudo is necessary do it, else go local user.
Upvotes: 2