I am using Terminal or iTerm (iTerm2). Let's say I've typed in a command but haven't hit enter yet. Or maybe I used the up arrow to navigate through my command history. How do I copy the current command to the MacOS clipboard? But I also don't want it to include the prompt. Is there a keyboard short cut to do this?
For example, let's say the terminal is showing this:
myhostname:Documents kevuser$ mkdir cool_directory_name
What is the keyboard shortcut to copy mkdir cool_directory_name
to the Mac OS clipboard? Can I add that functionality somehow? It feels like every time I try to copy the whole line it includes the prompt part of the terminal, myhostname:Documents kevuser$
, which I don't want to be copied and pasted.
Best Answer
Just use the command
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
If you want to copy text that you’ve entered but not executed you can use the following
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.