Access the Clipboard Through the Terminal in macOS

macOS provides a very handy way to share data between graphical (GUI) applications and command-line (terminal) tools.

This is especially useful for working with APIs using JSON (or XML) which require large payloads.

The two binary commands are pbcopy and pbpaste: short for Pasteboard Copy and Pasteboard Paste respectively (the macOS term for Clipboard).

  • pbcopy takes the standard input and copies it to the pasteboard
  • pbpaste takes the pasteboard data and copies it to the standard output

Suppose we have a sample payload in file.json. We can send its contents to the clipboard by piping the data to pbcopy:

$ cat file.json | pbcopy

Now, we simply press Command+v in a GUI app like Postman or Insomnia.

In reverse, we can press Command+c in a GUI app and then in the terminal:

$ pbpaste
{
  "data": "test"
}

Or, redirect the standard output to a file:

$ pbpaste > file.json

Or, pipe the data straight into a another command, like the super-handy JSON viewing tool fx:

$ pbpaste | fx

Note that these commands are macOS specific; they do not exist in Linux.

Leave a Reply

Your email address will not be published. Required fields are marked *