tl; dr: Use history -p \!-{4..1}
If the only reason you want to copy them is so you can run them again, you may want to simply use history expansion. (Run LESS='+/^history expansion' man bash
to see the man page for this.)
For instance, let's say I want to rerun the last four commands. I can just type:
!-4; !-3; !-2; !!
If I'm not completely sure it was the last four commands and I want to verify what those commands were before I run them, I can use the modifier p
to print the expansion and add it to my history without actually running it:
!-4; !-3; !-2; !!:p
(Putting it on any one history expansion is enough; nothing will get run thereby.)
Now if I'm happy with it, I just press the "up" arrow and press "enter".
If I want to save a command to a file for later reference, I use the -p
option to the history
command. First I will usually get the history number of the last command, for instance by running history | tail
. Let's say that looks like this:
$ history | tail
1136 cd /tmp
1137 ls
1138 cd -
1139 pwd
1140 cp somefile ~-/
1141 ping somesite.com
1142 printf '%*.*s\n' 0 "$(tput cols)" "$(printf '%0.1s' -{1..$(tput cols)})"
1143 for ((i=1;i<=3;i++)); do awk -F: -vi="$i" '{if (NR != 1) {printf ":"} {printf "%s",$i}} END {printf "\n"}' input; done | column -t -s:
1144 cd ~/documents
1145 history | tail
If I want to save the long for
loop command (line 1143) for later use, I can do so easily using history -p
as follows:
$ history -p \!1143 >> my_list_of_one_liners.sh
Note that history -p
itself does not appear in the history list.
Also note that history -p
can accept multiple arguments, and will expand each on a separate line. So really this is the best answer to your question, which I now realized.
Run history -p \!-{4..1}
and you will see the last four commands you ran printed to your terminal with no preceding numbers, perfect for copying. The 4
can be replaced by any number you like.
help history
to see it.man history
works find on my machine but there is about 20 mins of readable material and I was wondering if anyone knew the answer quickly, SO style.