I want to see what are the last N commands in my history. I thought history | tail -n 5 would make it, but I noticed that a multiline command counts for as many lines as it has.

$ echo "hello
how are you"
$ history | tail -2
how are you"
1051  history | tail -2

So my question is: do I have to parse the output of the command to accomplish this?

  • 1
    // , This is why I love stackexchange – Nathan Basanese Mar 7 '18 at 20:53

I found it!

history [n]

An argument of n lists only the last n lines.

$ echo "hello
how are you"
$ history 2
1060  echo "hello
how are you"
1061  history 2
  • 5
    That seems to be for tcsh, yash and bash. You may want to give the corresponding information for other shells like zsh, fish, ksh, and the POSIX way. – Stéphane Chazelas Jun 29 '15 at 14:59
  • 1
    I would love to, although I don't have any of these installed in my computer. Do you recommend any specific source to get the information from? In opengroup I see a reference to pubs.opengroup.org/onlinepubs/9699919799 – fedorqui Jun 29 '15 at 16:01
  • 7
    fc -l -2 works too (but doesn't add current fc -l -2 to output) – Evgeny Vereshchagin Jun 30 '15 at 3:44
  • fc by the way shows the last n commands with -n. Showing from n commands until last is only n (which does not make much sense because you need to know the total number). In german we would say ein kleiner aber feiner unterschied: A small but delight diff. Do not forget to use -l as @EvgenyVereshchagin pointed already because otherwise you end up in an editor which is not what you want. – Timo Mar 13 '18 at 20:44

You could also use negative numbers, like :

history -1

Or use a range (last 10):

history -1 -11 
  • 1
    Doesn't work for me with bash 5.0.11. – joelostblom Oct 6 '19 at 21:10

When you apply history it will show last history command as well. To prevent that space waster such alias could be handy:

alias hs=' history 16 | head -n 15'

(the command itself history 16 | head -n 15)

Another useful history alias:

  alias hsg=' history | grep ' 

(when ctr+R is too small to choose from)

The space in front of _history will run command not written in history

fc -l # will also list 16 last commands (and more)

  • 2
    While true, none of this addresses the question at hand. – Jeff Schaller Feb 2 '19 at 3:33

Tested in OpenBSD 6.3 (PD KSH v5.2.14 99/07/13.2).

history [b]

Shows all the history beginning from an entry with a number [b]

history [b] [e]

Shows the history interval from [b] to [e]

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.