Ubuntu – Alternative way to run a sudo command on startup

bashbashrcbatteryhibernatesudo

I am trying to write a script for my Ubuntu system to hibernate, whenever the amount of battery left is (say) 5%. This script will run on startup.

I can get the battery left using

upower -d |grep perc

Then I wish to use

sudo pm-hibernate

whenever battery reaches <= 5%. But this requires superuser permission. AND I DON'T WANT TO TYPE PASSWORD AGAIN AND AGAIN AFTER EVERY LOGIN.

One way is to use add the following line in /etc/sudoers

yourlogin ALL=(ALL) NOPASSWD: command_here 

But most people recommend against that.

Another way is to add a custom startup script in /etc/init.d. But I am not sure whether it is a safe choice.

Also, is there any other alternative which would be best for my purpose?

Best Answer

Simpler than adding a script to init.d is to write an Upstart configuration. I'd favour this above all. Create a .conf file in /etc/init (say /etc/init/sleep-on-suspend.conf, containing:

description "Automatic suspend"

start on runlevel [2345]
stop on runlevel [016]

exec /path/to/script

This will be automatically started on reboot.

You could even integrate the script into this file. Instead of the exec line, use:

script
    while sleep 1; do
    upower -d | awk -F'[ %]*' '/perc/ && ($3 < 5) { exit 1 }' || pm-hibernate
    done
end script