Created
July 19, 2025 10:35
-
-
Save felipealfonsog/9f6b77bf61fc3201a50084000ed7442d to your computer and use it in GitHub Desktop.
sudo bash setup-battery-hibernate.sh
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -e | |
echo "🔧 Creating 8G swap file at /swapfile..." | |
sudo fallocate -l 8G /swapfile | |
sudo chmod 600 /swapfile | |
sudo mkswap /swapfile | |
sudo swapon /swapfile | |
echo "💾 Adding swap to /etc/fstab if not present..." | |
grep -q "/swapfile" /etc/fstab || echo "/swapfile none swap defaults 0 0" | sudo tee -a /etc/fstab | |
echo "⚙️ Creating battery check script..." | |
sudo tee /usr/local/bin/battery-hibernate.sh > /dev/null <<'EOF' | |
#!/bin/bash | |
LOGFILE="/var/log/battery-hibernate.log" | |
BATTERY_FILE="/sys/class/power_supply/BAT0/capacity" | |
if [ ! -f "$BATTERY_FILE" ]; then | |
echo "$(date): Battery info file not found. Exiting." >> "$LOGFILE" | |
exit 1 | |
fi | |
BATTERY=$(cat "$BATTERY_FILE") | |
echo "$(date): Battery at $BATTERY%" >> "$LOGFILE" | |
if [ "$BATTERY" -le 5 ]; then | |
echo "$(date): Critical battery level ($BATTERY%). Hibernating..." >> "$LOGFILE" | |
systemctl hibernate | |
else | |
echo "$(date): Battery level ok. No action taken." >> "$LOGFILE" | |
fi | |
EOF | |
sudo chmod +x /usr/local/bin/battery-hibernate.sh | |
echo "🛠️ Creating systemd service..." | |
sudo tee /etc/systemd/system/battery-hibernate.service > /dev/null <<EOF | |
[Unit] | |
Description=Hibernate system when battery is critical | |
After=multi-user.target | |
[Service] | |
Type=oneshot | |
ExecStart=/usr/local/bin/battery-hibernate.sh | |
EOF | |
echo "⏲️ Creating systemd timer..." | |
sudo tee /etc/systemd/system/battery-hibernate.timer > /dev/null <<EOF | |
[Unit] | |
Description=Check battery level every 2 minutes | |
[Timer] | |
OnBootSec=1min | |
OnUnitActiveSec=2min | |
Unit=battery-hibernate.service | |
[Install] | |
WantedBy=timers.target | |
EOF | |
echo "🚀 Enabling timer..." | |
sudo systemctl daemon-reexec | |
sudo systemctl daemon-reload | |
sudo systemctl enable --now battery-hibernate.timer | |
echo "✅ Done. Battery hibernation active at 5%." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment