[Linux] Play a warning sound when your laptop battery is low

Image Source: https://www.flickr.com/photos/weishaupt-cycles/8738377068
  1. Download a short warning sound from anywhere on the Internet. (if you like you can even play a whole song 😀 but remember, that could drain your battery even more if you are not near it to plug it back).
  2. Install the command line music player `mpg123` by running the following commands in your terminal.
sudo apt-get update -y
sudo apt-get install -y mpg123
#!/bin/bash# You need to export this environment variable in order to play sound from cron
export XDG_RUNTIME_DIR="/run/user/1000"
currentBatteryPercentage=$(upower -i /org/freedesktop/UPower/devices/battery_BAT0 | grep "percentage" | awk '{print $2}')currentBatteryPercentage=${currentBatteryPercentage/\%/}if [ $currentBatteryPercentage -lt 22 ]thenmpg123 /home/kasun/Music/apx_battery_low_aler.mp3 -l 2fi
  • If upower is not installed in your system run the following commands for installing upower .
sudo apt-get update -y
sudo apt-get install -y upower
  • Replace mpg123 ‘s argument with the path to your downloaded music file (mine is located at `/home/kasun/Music/apx_battery_low_aler.mp3`)
crontab -e
*/5 * * * * bash /home/kasun/Documents/Scripts/battery-low.sh
  • Provide the path to your script file after the sh command (mine is located at `/home/kasun/Documents/Scripts/battery-low.sh`)
  • You can change the scheduled time to anything you want.
  • Please refer https://kb.iu.edu/d/afiz for more details on the crontab.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store