Copy the output of the last command in Terminal.app

!! | pbcopy would also run the commands again and couldn't be used with interactive commands.

This relies on the prompt always being $ :

tell application "Terminal" to tell window 1 to history
do shell script "/bin/echo " & quoted form of result & ¬
    " | ruby -e 'puts $<.read.split(/^\\$ .*?$/)[-2][1..-1]'"
set the clipboard to result

Does anyone know any better options?


If you are using at least el Capitan you can use Cmd-shift-A to select the output of the last command and Cmd-C to copy it. Unfortunately this doesn't work for previous versions.


Edited to add updates from the comments:

  • this also works for other than just the latest command: first select any part of the output of any previous command manually, and then hit Cmd + Shift + A
  • after trying this shortcut in iTerm, it asks to install some Shell Integrations and then this keyboard shortcut starts working in iTerm as well, see https://superuser.com/a/1242752/676978 for more details