In Yosemite the following oneliner (built on this answer) works:
killall Dock \
&& sleep 0.1 \
&& defaults export com.apple.spaces - \
| plutil -convert json - -o - \
| jq '.SpacesDisplayConfiguration."Management Data".Monitors[0] | ."Current Space".uuid as $current_desktop_uuid | [.Spaces[].uuid]|index($current_desktop_uuid)'
(Requires jq
version 1.5 for whitespace-containing key access, installable with e.g. Homebrew.)
On my Desktop 3 this oneliner will output:
$ killall Dock && sleep 0.1 && defaults export com.apple.spaces - | plutil -convert json - -o - | jq '.SpacesDisplayConfiguration."Management Data".Monitors[0] | ."Current Space".uuid as $current_desktop_uuid | [.Spaces[].uuid]|index($current_desktop_uuid)'
3
Rationale: as described in this answer, the desktops and their contents are stored in ~/Library/Preferences/com.apple.spaces.plist
. However, this file isn't automatically updated when changing the desktop. So, to get the current desktop number we
- enforce the desktop property list update with
killall Dock
. It takes a moment for the data to be stored to the disk so
- wait for 0.1 seconds (enough on my machine) for the file to be written onto disk.
- Then export the updated desktop property list using
defaults
as XML,
- use
plutil
to convert the XML to JSON (a personal preference)
- and extract with
jq
the current space uuid and get its index in the space uuid list. Since the space uuid list contains Mac OS X Dashboard, the resulting index is exactly the number of the current desktop.
Note: This snippet did get the desktop number of my primary monitor on Yosemite – my colleague tested this on El Capitan with a different setup with no luck. But assuming that killall Dock
still works, the JSON output should still contain the relevant information.