My old laptop has a faulty battery, which shows 100% when on AC power but when unplugged it dramatically drops to random percentages within seconds and makes the machine turn off brutally. I am afraid of damaging my SSD (and my HDD) on which Ubuntu is loaded.
I wanted to turn the PC off as soon as the AC power is not available. I searched here and found this. But I don't understand the answer for that question or atleast it is relevant to my situation.
Please explain me a way to shut down my laptop automatically as soon as the AC power is unplugged or when there is a power failure.
Create a new rule in udev by opening the terminal and using:
(If you are using Ubuntu 18.04 or a newer version
gksu
will not be available by default. In that situation please refer this question or use the above command assudo -H gedit /etc/udev/rules.d/50-ac-unplugged.rules
)Put in the following line:
Save the file and then restart udev services with:
Save all your work and unplug your power supply.
Introduction
The script that has been discussed in the comments was written in bash and a while back. Since then I have made a different implementation of it in Python and using several utility functions which use dbus. All the technical gibberish aside, the script below is basically modified version of that Python script.
The key parts of the process are all done in the
main()
function. The whole bunch of other lines of code are utility functions, so the code might look slightly intimidating, but it is really not and isn't doing anything spectacular. There's a few extra error-checks made just in case,too.The idea of how it works is simple:
Setting up the script
First of all, obtain the script source code and save it as a file, preferably in your home folder, in
~/bin
to be exact. If you don't havebin/
folder in your home directory, create one.Save the script as
shutdown_monitor.py
and make sure it is executable either via right clicking on it in file manager or usingchmod +x ~/bin/shutdown_monitor.py
command in terminal.Finally, let's make the script start automatically when you log in. Open Unity Dash and find
Startup Applications. Add either full path to the command or
python /home/USERNAME/bin/shutdown_monitor.py` as new command.That's it !
Script
Also available as gist on GitHub
Additional notes
Please report bugs, if you find any, preferably here in the comments or on github