Everytime I need this I google it like 10 minutes. I don't know how to express this better so that Google finds it right away but I need to retrieve bash history between certain lines like:

$ history --start 321 --end 456
#to retrieve history from 321 and to 456

4 Answers 4


You can use something like

history | grep -A 135 -w 321

It starts with line 321 and shows the next 135 lines, so it will show lines 321 to 456.


Use head and tail:

history | head -n 456 | tail -n 136

Which will get the first 456 (up to the end you want) and then you get the last 136 (which computes as 456 - 136 = 320, but will fetch from the 321st record from history).

  • This isn't quite right since the command numbers don't equal line numbers. I'm assuming OP is asking command numbers. If you hit enter with empty command line, or run the same command multiple times, these aren't put into the history file but the command numbers are increased.
    – Aerith
    Oct 7, 2022 at 18:25
  • @Aerith please explain with an example, history has different options, you can discard duplicates or not, empty.lines usually are not in the history as being ignored...
    – Zina
    Oct 8, 2022 at 19:29

I assume you mean command numbers and not line numbers. I would use sed to give me the lines in the file between the two command numbers.

$ history | sed -n '/^ 321 /,/^ 456 /p'

^ character matches at the start of the line. Also a space after the number to make sure ^ 321 doesn't match line equalling 32155 ls

  • I was meaning line numbers but thank you for your contribution, it's worth to look at.
    – duru
    Oct 12, 2022 at 17:58

The solution below strives for the least dependencies, least mathematical calculation, maximal readability(tested under GNU grep):

# Display history lines exactly from line321 to line456
history | grep -A $((456-321)) '321\ \ '

# Or throw away 'Space Escaping', a even 
# more simple command we'd get , but the output 
# will contain one more line, which is this command itself.
history | grep -A $((456-321)) '321  '

with output:

321 some-command
322 some-command
456 some-command
  • What's so special about GNU grep? Even busybox grep has the -A command line option. Feb 25 at 14:30
  • @CristianCiupitu Thanks for pointing it out. I have refined the wording. Feb 26 at 13:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .