Bash – How to put the last zsh command in history into a clipboard

bashhistoryshellzsh

It often happens to me, that I just used a command and I need to copy/paste it either to a different terminal window/IM or whatever.

On a Mac, I can use the pbcopy command to get something in clipboard, but I'm not sure how should I get to the command. What I've came up is

history | tail -n 1 | perl -ple 's/\d+\s+//' | pbcopy

which works, but it doesn't really seem like clean solution. Is there a better way to get to the last command? I'm using zsh, but I guess if there's a solution for bash it will work in zsh too.

Best Answer

As a one-off for the last command:

echo !! | pbcopy 

will put exactly the last command into the clipboard.