Mac Terminal or iTerm: Copy the current command but exclude prompt?

Solution 1:

Just use the command

 echo !! | pbcopy

The double exclamation points is “last command”. It’s then piped to the pbcopy command which puts it in your clipboard.

There’s no shortcut, but you can make an alias in your ~/.bash_profile or in your ~/.zprofile files, depending on your shell, that will execute the command with as easy to remember name

alias cplastcmd=‘echo !! | pbcopy’

If you want to copy text that you’ve entered but not executed you can use the following

  • ^ ControlU : Cut the line before the cursor and put it in the clipboard.
  • ^ ControlK : Cut the line after the cursor and put it in the clipboard. Use with ^ ControlA to move to the beginning of the line.
  • ^ ControlY : Paste the last command from the clipboard

Note: The standard copy/paste keyboard shortcuts ⌘ Command or ^ Control C and V don’t work in Terminal.

Finally, if you have a mouse with a third/middle button, you can simply select the text and press the middle button to copy and paste the selected text.