Move Dock to another screen edge when unplugging monitor

When I exclusively use my laptop screen I prefer to have the Dock on the left edge, but when I plug in my external monitor I'd like to move the Dock to it instead.

Since my external screen is to the right of the laptop, the Dock will only appear on it if configured to appear on the bottom or right edge of the screen. As long as it's set to the left edge it remains on the laptop screen.

How do I accomplish this automatically whenever the external screen is (dis-)connected?

The solution mentioned here has nasty side-effects like unminimizing all my windows after killing the Dock:

defaults write com.apple.Dock orientation -string bottom
killall Dock

Use ControlPlane to run the following shell script whenever the state of the monitor connection changes:

move dock to bottom.sh:

#!/bin/bash

osascript -e '
tell application id "com.apple.systemevents"
    tell dock preferences
        set screen edge to bottom
    end tell
end tell
'

Duplicate the file, where you replace bottom with left.

Set up ControlPlane

  1. Create two ControlPlane contexts: Laptop screen only and External monitor.
  2. Enable the 'Attached Monitor' evidence source.
  3. Create two 'Attached Monitor' rules – one negated -- that switch to the corresponding context with 100% certainty when they fire.
  4. Create two actions that run the two shell scripts On arrival to their corresponding contexts.