Prevent Spotlight from indexing external drive

You could have a script that runs at startup that employs the technique suggested in this post https://apple.stackexchange.com/a/91759/183505

When booting from DriveA (when you want to disable spotlight indexing for External DriveB) you could execute :

touch /Volumes/DriveB/.metadata_never_index

When booting from external DriveB and you want to re-enable spotlight perhaps you could have your startup script execute:

rm /Volumes/DriveB/.metadata_never_index

The linked post also lists other ways to programatically alter the spotlight exclusions.

Here are some ways to add a script that will launch at login : https://stackoverflow.com/questions/6442364/running-script-upon-login-mac

Good luck!


Edit : Method using bash scripts and plist files


First create a startup script. I chose to create one at ~/script.sh

Make sure it's executable chmod +x ~/script.sh

Script for OS that wants to hide a drive from spotlight

#!/bin/bash
flagLocation="/Volumes/DriveToHide"
flagRemoved=".ney_the_index"  # a new name

# if flag exists rename it.
if [ -a "$flagLocation/.metadata_never_index" ]; then 
    mv "$flagLocation/.metadata_never_index" "$flagLocation/$flagRemoved";
fi

Script on the OS that wants to index the drive

#!/bin/bash
flagLocation="/Volumes/DriveToHide"
flagRemoved=".ney_the_index"

if [ -a "$flagLocation/$flagRemoved" ]; then
    mv "$flagLocation/$flagRemoved" "$flagLocation/.metadata_never_index"
fi

if [ ! -a "$flagLocation/$flagRemoved" ] || [ ! -a "$flagLocation/.metadata_never_index" ] ; then
    touch "$flagLocation/.metadata_never_index"
fi

Create a plist file ~/Library/LaunchAgents/com.user.loginscript.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
   <key>Label</key>
   <string>com.user.loginscript</string>
   <key>Program</key>
   <string>/Users/yourusername/script.sh</string>
   <key>RunAtLoad</key>
   <true/>
</dict>
</plist>

Test it by loading and unloading it:

launchctl load ~/Library/LaunchAgents/com.user.loginscript.plist

I learned today that you can use a sudo touch /.metadata_never_index_unless_rootfs in the root directory of each drive to separate Indexes from OS X Boot-Drives. It is a special version of .metadata-never-index, because it will (re)index the drive when you boot from it, but not when you don't.