95

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?

fedorqui
  • 7,861
  • 7
  • 36
  • 74

4 Answers4

105

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
fedorqui
  • 7,861
  • 7
  • 36
  • 74
  • 11
    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 http://pubs.opengroup.org/onlinepubs/9699919799/ – fedorqui Jun 29 '15 at 16:01
  • 9
    fc -l -2 works too (but doesn't add current fc -l -2 to output) – Evgeny Jun 30 '15 at 03:44
  • 1
    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
  • 1
    fc can hide line number also. Eg: fc -ln -1 will get the last command without line number – feng zhang Aug 07 '20 at 10:25
14

You could also use negative numbers, like :

history -1

Or use a range (last 10):

history -1 -11 
robertrv
  • 149
  • 1
  • 2
  • 3
    Doesn't work for me with bash 5.0.11. – joelostblom Oct 06 '19 at 21:10
  • 2
    This is the way for zsh! – Ansjovis86 Nov 12 '21 at 16:53
  • Does not work for me on Linux Mint 20.02 with GNU bash, Version 5.0.17(1)-release (x86_64-pc-linux-gnu): "invalid option." In German: bash: history: -1: Ungültige Option. history: Aufruf: history [-c] [-d Offset] [n] oder history -anrw [Dateiname] oder history -ps Argument [Argument...] – questionto42 Dec 13 '23 at 22:04
6

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)

1

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]