How to disable Spotlight indexing when on battery?

jherran's answer helps you with disabling Spotlight indexing, but does not address the part of the question about toggling automatically when AC power is connected or disconnected.

You could use sudo mdutil -i off / and sudo mdutil -i on / in conjunction with a listener for when AC power is disconnected. Using something like ControlPlane will satisfy your requirement for automatic toggling. It supports "Current power source" as an event to listen for. It is free and open source.

You might be against using a third party solution. To roll your own, try writing a script that loops checking pmset -g ps | grep -c 'AC Power' with a sleep interval in between. If AC is connected, it outputs 1 (0 otherwise).


I wrote this script (/Users//bin/control_spotlight_indexing.sh) to toggle on/off indexing based on power source. I also set it up to run as root in a cron job (executed as /Users//bin/control_spotlight_indexing.sh >> /Users//bin/control_spotlight_indexing.log).

Suggestions for improvements are welcome.

#!/bin/zsh

# Turn on Spotlight indexing by default
mdutil -i on /

# Power: 0 is battery; 1 is charger.
power=$(pmset -g ps | grep -c 'AC Power')

while [ true ] ; do

  if [ $power -eq 0 ] ; then
    # Turn off Spotlight indexing
    mdutil -i off /
    # Check every hour
    while [ $power -eq 0 ] ; do 
      time=$(/bin/date)
      echo "[$time] Battery: Spotlight indexing is OFF. Will check again 1 hour."
      sleep 3600
      power=$(pmset -g ps | grep -c 'AC Power')
    done
  fi

  if [ $power -eq 1 ] ; then
    # Turn on Spotlight indexing while on charger
    mdutil -i on /
    # Check every 10 minutes
    while [ $power -eq 1 ] ; do 
      time=$(/bin/date)
      echo "[$time] AC Power: Spotlight indexing ON. Will check again in 10 minutes."
      sleep 600
      power=$(pmset -g ps | grep -c 'AC Power')
    done
  fi

done