Script to play a warning when battery level is under a threshold in MacOS
13:08 01 Jan 2019

I am using a MacBook and the battery is unreliable. I am trying to find a script command that will enable the laptop to play a beep when the battery level is lower than a threshold. After some search and tests, I found a quick solution below:

1) I first create a file called check_battery with the following contents:

ioreg -l | awk '$3~/Capacity/{c[$3]=$5}END{OFMT="%.3f";max=c["\"MaxCapacity\""]; bat= (max>0?100*c["\"CurrentCapacity\""]/max:"?"); printf("%d", bat)}'

2) I then created the following file:

\#!/bin/bash
sh check_battery>battery;
let t=60
read a < battery
if(( "$a" < "$t" ));
  then
  say "Battery level is lower than 60%!";
  say "BEAP BEAP"
fi;

3) Finally, I try to add it to my crontab job, but crontab has been stopped by iOS. Then I found that I have to use launchd, which is detailed below: https://alvinalexander.com/mac-os-x/mac-osx-startup-crontab-launchd-jobs

It is now working at my MacBook labtop but there may be better solutions. Do share with me if you have other solutions. Many thanks.

bash macos scripting applescript battery