Grant superuser privilege for specific comands - kdaisho/Blog GitHub Wiki
If you're using a Linux laptop and find that suspend drains your battery excessively (e.g., around 4% per hour), hibernation might be a better alternative. Hibernation consumes no battery as it effectively powers off the machine while saving your session state to disk, allowing you to restore everything when you power back on.
While you can hibernate your system by running:
sudo systemctl hibernate
having to enter your password each time can be inconvenient. Luckily, you can override the privilege requirement for this specific command using polkit.
1. Use Polkit to modify rules
Polkit is built into Ubuntu and many other Linux distributions. You can create a custom rule to allow hibernation without requiring a password. Run the following command:
echo 'polkit.addRule(function(action, subject) {
if (action.id == "org.freedesktop.login1.hibernate" ||
action.id == "org.freedesktop.login1.hibernate-multiple-sessions") {
if (subject.isInGroup("sudo") || subject.user == "'$(whoami)'") {
return polkit.Result.YES;
}
}
});' | sudo tee /etc/polkit-1/rules.d/85-hibernate.rules && sudo chmod 644 /etc/polkit-1/rules.d/85-hibernate.rules
2. Test your setup
After creating the rule, you can test it by running:
systemctl hibernate
Your system should immediately hibernate without prompting for a password.
3. Optional: Create an alias
To make it even easier, you can create an alias for the command. Add this line to your shell configuration file (e.g., ~/.bashrc or ~/.zshrc):
alias hibernate='systemctl hibernate'