Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question

As a one-off for the last command:

echo !! | pbcopy 

will put exactly the last command into the clipboard.

share|improve this answer
This is a very nice trick! +1 – Yanick Girouard Feb 28 '12 at 13:03

You can use xclip for this task
See here
Your can just pipe something into the clipboard like this:

history 2 | xclip
share|improve this answer
xclip requires a X11 session... – Yanick Girouard Feb 28 '12 at 13:07
If you read the question carefully, you will notice this part of the first sentence: "I need to copy/paste it either to a different terminal window/IM or whatever.". Doesn't that imply that he has a X Session? – Niko S P Feb 28 '12 at 13:15
No, it implies he has a window session, which may be X, but it also may be unity, NeWS, or any of the other gui interfaces one may have to a system. – hd1 Mar 23 at 0:05

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.