copy last command in terminal
I can see the last command in the terminal by pressing up arrow
as in the following example:
I typed cd /
:
Makss-Mac:~ maks$ cd /
... pressed enter
, command cd /
executed and now I can press up arrow
and see the command cd /
again:
Makss-Mac:/ maks$ cd /
I want to not only see the last command but also copy it to the clipboard.
Maybe there exists a shortcut that not only shows the last command in the terminal (as up arrow
does) but at the same time copies it to the clipboard.
Or maybe there is a shortcut for selecting all from current terminal line. And so I would be able to copy the last command (after pressing up arrow
) by pressing super+c
. Of course I can select it with the mouse. But when commands are 10 times longer than cd /
it can be too time-consuming, especially if you do it every 30 seconds.
Or is there maybe a way to write a plugin for the 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"):
- Execute any command in tab A
- Switch to tab B, press enter on an empty line, giving you a "fresh" new line (and thus re-evaluating the history)
- 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
I came here as came up with Sam Berry's exact same answer, but it doesn't work for me (OSX 10.14.6).
Managed to get it to do so with quotes around the !!
:
echo "!!" | pbcopy