=> Front page
Published: 2024-12-29
I love automation—not just home automation but anything that simplifies my life. For example, I use a Shortcut on my iPhone that automatically turns on Low Power Mode when the battery drops below a certain percentage.
This morning, while working on my laptop, I realized that macOS allows Low Power Mode to be set to "always on" when on battery power, but it doesn't provide an option like "only when the battery level is below X%." Naturally, I decided to create a script to achieve the same functionality on my laptop that I already enjoy on my phone.
After a quick search, I found the commands needed to set the power mode and check the battery level. Another search revealed that macOS supports allowing specific users to execute scripts with sudo privileges without needing a password. 💥 A few minutes later, I had my laptop automatically enabling or disabling Low Power Mode based on the battery percentage. 🤓
Here's how you can achieve the same result.
First, create a script to check the current battery level and set the Low Power Mode accordingly. I like to save my scripts in $HOME/bin
. On my laptop, that's /Users/Erick/bin
. So, I created a script at /Users/Erick/bin/low-power-mode
with the following contents:
#!/usr/bin/env bash # Get the current battery level _level=$(pmset -g batt | grep "InternalBattery" | awk -F '[\t;]' '{print $2}') # Remove "%" symbol from the battery level _level=${_level/\%/} # Get the current Low Power Mode state _current_mode=$(pmset -g | grep lowpowermode | awk '{print $2}') # Initialize the new mode variable _new_mode= # Enable Low Power Mode if the battery level is <= 10% if [ $_level -le 10 ]; then _new_mode=1 # Disable Low Power Mode if the battery level is >= 25% elif [ $_level -ge 25 ]; then _new_mode=0 fi # Update the Low Power Mode state if it differs from the current state if [ "$_current_mode" != "$_new_mode" ]; then pmset -a lowpowermode $_new_mode fi
Make your script executable with the following command:
chmod +x /Users/Erick/bin/low-power-mode
The pmset
command requires root privileges, and since the script will run automatically, it needs to execute without prompting for a password. To achieve this, update the sudoers file:
sudo visudo
%admin ALL = (ALL) ALL
%admin ALL = (ALL) NOPASSWD:/Users/Erick/bin/low-power-mode
To run the script automatically, schedule it using cron:
crontab -e
* * * * * sudo /Users/Erick/bin/low-power-mode
And That's It!
Now, your laptop will automatically check the battery level every minute and adjust the power mode accordingly. Whether you're a beginner or a seasoned scriptwriter, this approach ensures your laptop's energy efficiency is always optimal.
=> LinkedIn | GitHub | Fediverse
© 2025 Erick Ruiz de Chavez
text/gemini;lang=en
This content has been proxied by September (ba2dc).