Automate saving screenshot (already in clipboard) to a file in bash

automatorbashscreen capture

I work on the command line quite a bit and often have to take a screenshot a region of the screen and save it to directory I am currently working in.

(let's assume I've already taken the screenshot and clipboard has it).

This is how I have to do it right now (after have the screenshot in clipboard):

  1. launch Preview.
  2. in Preview, ⌘ + N (File, New from Clipboard) creates a new file with the clipboard contents.
  3. go back to command line and copy the directory name (copy the results of pwd)
  4. go to Preview, ⌘ + S for Save. Type / gets me a directory navigation prompt where I can paste my directory name from step 3.
  5. Finally, give the actual file name, this_is_where_I_get_the_error.png in my example.

I'd like to do this instead:

$savemyscreenshot ./this_is_where_I_get_the_error.png

How would I go about writing that savemyscreenshot command? In bash? As an Automator script (which has to be callable from the Terminal, else that defeats the purpose somewhat)?

All things being equal, would slightly prefer a javascript flavor of the Automator script over AppleScript.

env: MacOS Sierra

Best Answer

  • screencapture is a CLI tool built into macOS for taking screenshots, in /usr/sbin/screencapture.

    To take a screenshot and save it to screenshot.png:

    screencapture -x screenshot.png

    To screenshot a region, you can use -R, where x,y are the coordinates of the top-left and w,h is width and height of the capture.

    screencapture -x -Rx,y,w,h /path/to/capture.png

    To interactively choose a region, use -i

    screencapture -i screenshot.png