How to take a screenshot of the front window from the command line

screen capture

The screencapture utility has a -w switch which allows capturing the front window, but only after highlighting the window and getting a click from the user.

Is there any way to capture the front window non-interactively using some shell command?

Best Answer

The -l option allows capturing a window by ID. It is only shown in the help message and not on the man page.

I don't know any way to find the window IDs that would work with all applications though. This doesn't work with Preview, Activity Monitor, or Chrome:

screencapture -l $(osascript -e 'tell application (path to frontmost application as text) to id of window 1') /tmp/screencapture.png