30

The history command lists out all the history for the current session. Like:

1 ls 
2 cd /root
3 mkdir something
4 cd something
5 touch afile
6 ls
7 cd ..
8 rm something/afile
9 cd ..
10 ls
11 history

In order to search items of interest, I can pipe history with grep like

history | grep ls
1 ls
6 ls
10 ls

I can also view last 3 commands like:

history 3
11 history
12 history | grep ls
13 history 3

But how do I get a specific range of history? For example something like:

history range 4 7
4 cd something
5 touch afile
6 ls
7 cd ..
  • You could list the last x commands then pipe to head. – Bratchley Jun 22 '16 at 3:52
  • @Bratchley: For that I'd have to know how many last commands to go to. Consider this, my history | grep something shows results of commands numbered 123 234 345 in history and I may not know the number of last command executed (history in this case). My last command could be numbered 400, 500 or whatever. So first I have to check that number, figure out the difference, list the last x commands and then pipe to head – Slartibartfast Jun 22 '16 at 3:59
52

Instead of history, you can use fc, which allow you select range:

fc -l 4 7
  • 4
    It even accepts negative numbers to count from the end, like fc -l -16 -10. – Franklin Yu Jun 22 '16 at 8:39
  • hmm, wonder why we need a whole new command instead of just arguments to the actual command... – Ringo May 10 at 1:56
10

If you must use history command, pipe it through sed or awk:

history | sed -n '10,20p'

history | awk 'NR >= 10 && NR <= 20'

Otherwise cuonglm's answer is better option.

  • 6
    Since we're into bad alternatives, a combination of head and tail would solve this problem in an even less elegant way. For the range 10->25 you'd have to use history | head 25 | tail 15. – Aaron Jun 22 '16 at 13:45
0

Using history with a grep on the line numbers around the command I'm looking for works best for me.

For instance I'm looking for what I did around ping mybox, more or less 20 lines.

$ history | grep "ping mybox" 20325 ping mybox

That's line 20325 so I just have to grep the lines starting by a number in the [20320..20339] range.

$ history | grep ^203[2-3][0-9]

  • (1) You say “more or less 20”, but your example shows −5 and +14.   (2) This doesn’t work for me, because history numbers seem to have leading spaces. – Scott Oct 6 '17 at 10:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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