Skip to content

Instantly share code, notes, and snippets.

@tomsoderlund
Last active January 24, 2021 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomsoderlund/c14b6fa789fd8f903e42388ea9d39e8a to your computer and use it in GitHub Desktop.
Save tomsoderlund/c14b6fa789fd8f903e42388ea9d39e8a to your computer and use it in GitHub Desktop.
macOS bash script to close all non-essential apps – like “Close all browser tabs” but for apps
#!/bin/sh
# Example: kill all non-development apps:
# . killapps.sh dev
# Example: kill all non-office apps in a soft way:
# . killapps.sh office soft
# Strip leading and trailing white space (new line inclusive).
trim () {
[[ "$1" =~ ^[[:space:]]*(.*[^[:space:]])[[:space:]]*$ ]]
printf "%s" "${BASH_REMATCH[1]}"
}
function killAllRunningApps {
runningAppsString=`osascript -e "tell application \"System Events\" to get the name of every process whose visible is true"`
while IFS=',' read -ra runningAppsArray; do
for appName in "${runningAppsArray[@]}"; do
appName=`trim "$appName"`
if [ "${excludeApps/$appName}" = "$excludeApps" ]; then
killApp "$appName" $killMethod
else
echo "NOT killing: $appName"
fi
done
done <<< "$runningAppsString"
}
# killApp appName softOrHard
function killApp {
# "title is" not working
foundApp=`osascript -e "tell application \"System Events\" to return every application process whose (name is \"$1\" or short name is \"$1\" or displayed name is \"$1\")"`
if [[ -n $foundApp && $foundApp != *", "* ]]; then
if [ "$2" = "hard" ] || ! [ "${alwaysKillHardApps/$1}" = "$alwaysKillHardApps" ]; then
# Hard kill
echo "Killing app (hard): $1"
pkill -9 "$1"
else
# Soft kill
echo Killing app: $1
osascript -e "tell application \"$1\" to quit with saving"
fi
fi
}
# Apps to exclude
if [ "$1" = "off" ] || [ "$2" = "off" ]; then
echo Killing only non-office apps
excludeApps="Finder,iA Writer,Slack,Terminal,Google Chrome"
elif [ "$1" = "dev" ] || [ "$2" = "dev" ]; then
echo Killing only non-development apps
excludeApps="Finder,iA Writer,Terminal,Sublime Text,Atom,GitHub Desktop,Simulator,Application Loader,Insomnia,MongoHub,Postico,Google Chrome,Slack,Figma"
else
echo Killing all apps
excludeApps="Terminal"
fi
# Kill hard or soft?
if [ "$1" = "hard" ] | [ "$2" = "hard" ]; then
echo Killing HARD!
killMethod=hard
else
echo Killing softly...
killMethod=soft
fi
# Always kill hard
alwaysKillHardApps="Skitch"
killAllRunningApps
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment