
Automatically Shutting Down Your Laptop at Low Battery Levels
Maintaining long battery life and protecting data are crucial for laptop users. In this article, we’ll show you how to create a simple Bash script that automatically shuts down your laptop when the battery level falls below 20%. Additionally, you’ll learn how to set up a crontab to run the script every 10 minutes, ensuring continuous monitoring.
Creating a Bash Script
The Bash script we have prepared will check the current battery level and compare it to a set minimum threshold. If the battery level drops below this threshold, the script initiates a system shutdown, helping to protect your data and hardware.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#!/bin/bash # Define the minimum battery level before shutdown MIN_BATTERY_LEVEL=20 # Get the current battery level current_level=$(cat /sys/class/power_supply/BAT0/capacity) # Check if the current battery level is less than or equal to the minimum level if [[ "$current_level" -le "$MIN_BATTERY_LEVEL" ]]; then echo "Battery level is $current_level%, which is below the threshold of $MIN_BATTERY_LEVEL%. Shutting down..." # Shutdown command /sbin/shutdown -h now else echo "Battery level is $current_level%, no need to shut down." fi |
Also you can download script:
1 |
wget https://soban.pl/bash/check_battery.sh |
Don’t forget to grant permissions to run it:
1 |
chmod +x check_battery.sh |
Crontab Configuration
Crontab is a tool that allows you to schedule tasks in the Linux system. With it, we can set up regular battery checks.
1 2 3 4 |
crontab -e # Add the following line to crontab to run the script every 10 minutes */10 * * * * /root/check_battery.sh > /dev/null 2>&1 |
Summary
With this setup, you can rest assured about the condition of your laptop even during intensive use. Automatic shutdown at low battery levels not only protects the equipment but also helps maintain a longer battery life.