Apple - copy last command in terminal

Put this into your ~/.bashrc ~/.bash_profile or where-ever you like it:

alias copyLastCmd='fc -ln -1 | awk '{$1=$1}1' | pbcopy '

After opening a new window (or running source ~/.bash_profile) you should be able to run copyLastCmd and have the command in the clipboard.

To explain what's going on: you're basically using "fix command" (fc) to get you the last command, remove both leading and trailing whitespace for nicer formatting with awk and then copy it into your Mac's pasteboard with pbcopy.

EDIT:

Now that we know that you want to copy to paste into another terminal tab, there's another option: Add these lines to your ~/.bashrc ~/.bash_profile or where-ever you like it:

shopt -s histappend
PROMPT_COMMAND='$PROMPT_COMMAND; history -a; history -n'

Then, once you have some new tabs open (let's call them "tab A" and "tab B"):

  1. Execute any command in tab A
  2. Switch to tab B, press enter on an empty line, giving you a "fresh" new line (and thus re-evaluating the history)
  3. use the up arrow once and you should have the command you've just entered in tab A.

EDIT 2: I've replaced the usage of sed with awk in the original answer above, to take care of both leading and trailing whitespace .


This will use history expansion to grab the last command and echo it. You can pipe to pbcopy to save the last command to your clipboard.

> echo !! | pbcopy

If you want a command from your history that was not the last one, you can run:

> history

And reference the desired command number like:

> echo !5 | pbcopy

Here's another take based on the answer by @Asmus. To make his alias work in my bash script, I had to use a bit of quoting, since single quotes don't work in a single-quoted alias without some additional quoting:

alias copyLastCmd='fc -ln -1 | awk '\''{$1=$1}1'\'' | pbcopy'

The '\'' will basically close the current quote, then add an escaped quote, and then open the actual quote again.

The above version will copy the last command to your clipboard, and once you paste it, it's immediately executed, since it will have a newline at the end.

To get rid of the newline at the end, so you can actually edit the command before running it, you can do the following:

alias copyLastCmd='fc -ln -1 | awk '\''{$1=$1}1'\'' ORS='\'''\'' | pbcopy'

The ORS='' (that's without the quoting) will strip off the trailing newline character, so you can edit the pasted text before running it.