Programmatically switching desktops in OS X

2015-01-30 10:29 PST

I have been using Spaces in OS X since the day they came to OS X. I love them dearly. Often I find that I will be deep in concentration, working on a task when somebody will come up to me, hair on fire with something they need taken care of right away. It used to be that when this occurred, I would have to rearrange the windows on my desktop to make space for the appropriate windows to solve the new “hair-on-fire” task. It meant that getting back to what I was doing was a challenge - I would have to set up my workspace for the previous task before I could get back to work on it.

Enter Spaces. When Apple brought Spaces to the Mac as part of Expose, I immediately found a use for them in my workflow. Now, I set up my machines with several spaces already open. The first one or two always contain Mail, Calendar, Messages, HipChat and Spotify. These are the apps I use every day; they are the hub of my computing experience. The other vacant Spaces are there for the tasks that I will work on throughout the day. This means that when I am writing a blog post or putting together a script, when somebody comes to me with their hair on fire I can just switch to a vacant space, solve their problems of the day, and switch back without messing up my windows and thus my workflow.

The next logical step for me was to create a script that starts up each of those “hub experience” programs each morning, and place each of them in the correct space. It turns out however that accessing those spaces programmatically is a bothersome thing - so after beating my head agains a wall and trying things like binding certain apps to certain spaces, I was finally able to put this gem together. Really it is a script in 2 parts.

start-the-day simply opens programs using open -a. This allows you to open GUI programs and files from the terminal. SOme programs take a bit of time to open and so I use sleep commands to prevent the shell from getting ahead of itself. The key to space switching lies in line 8. I source a script I wrote called switch.sh, which handles the Space switching for this script and for another script I wrote that uses some Space switching.

What switch does in a nutshell is use osascript to send an AppleScript command to “System Events” that simulates the keycode of a particular keyboard combination. So, as long as your desktops use the correct ‘standard’ keyboard mapping you can use switch 7 to switch to your seventh desktop. switch 13 will go to your thirteenth desktop, etc.

If you place switch.sh in your $PATH the you can use it directly from the command line, or within other scripts as I have done above.

While not the most elegant solution, this does indeed work, and should do for me, until Apple brings proper scripting access to Mission Control.