Bash – Should scripts that require sudo fail if they don’t have it, or use sudo and prompt

bashshell-scriptsudo

I have a script which gives me fine-grained control over my backlight brightness and requires sudo to run. It's essentially this:

backlight="/sys/class/backlight/acpi_video0/brightness"
echo $1 | tee $backlight

and lives at ~/bin/backlight-adjust. The script needs sudo privileges, because tee $backlight is writing to a privileged location. So it'll fail if it's not run with sudo.

This approach has a problem, because I can't just run sudo backlight-adjust, because ~/bin is not in the $PATH in the sudo environment, only in my environment. So I'd have to to run sudo env "PATH=$PATH" backlight-adjust or something similar.

Alternatively, I could have written it like this:

backlight="/sys/class/backlight/acpi_video0/brightness"
echo $1 | sudo tee $backlight

and prompt me for the password.

The second approach works better for me because I don't have to remember to type sudo; it'll prompt me. And I can keep my $PATH intact. This feels more convenient overall, but are there any reasons why I shouldn't do it the second way?

(I'm running Xubuntu 14.04 and my shell is GNU bash 4.2.45, if that makes a difference.)

Best Answer

Personally, I would use a different approach. Make an alias for your script. Add this line to your ~/.bashrc (or equivalent in other shells)

alias backlight-adjust='sudo ~/bin/backlight-adjust'

That way, you don't need to worry about remembering to run it with sudo and you don't need to add the sudo to the script. It will be completely transparent to you and simply ask for your password when you try and run backlight-adjust.