How can I run a script when the power supply is plugged-in or -out?
Solution 1:
You can use on_ac_power
to run a script when the power supply is turned on or off.
Try the following in a terminal.
$ on_ac_power
$ echo $?
0 ## Laptop on ac power
$ on_ac_power
$ echo $?
1 ## Laptop on battery (not on ac power)
Based on this you can make your script as,
#!/bin/bash
while true
do
if on_ac_power; then
do_something ## Laptop on power
else
do_something_else ## Laptop on battery
fi
sleep 10 ## wait 10 sec before repeating
done
EDIT:
cron job
would be a better idea for running the script at a regular interval instead of using an infinite loop.
Save your script as myscript.sh
and put the following content in it,
#!/bin/bash
if on_ac_power; then
do_something
else
do_something_else
fi
Make the script executable from a terminal, chmod +x /path/to/myscript.sh
. Open your personal crontab
as EDITOR=gedit crontab -e
and append the following line in it to run your script every minute.
* * * * * /path/to/myscript.sh