90

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?

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
fedorqui
  • 7,603
  • 7
  • 35
  • 71

4 Answers4

101

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,603
  • 7
  • 35
  • 71
  • 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 Vereshchagin Jun 30 '15 at 03:44
  • See also: [How to stop bash replacing commands in history with asterisks ? (‘*’)](http://unix.stackexchange.com/questions/36212/how-to-stop-bash-replacing-commands-in-history-with-asterisks). – Evgeny Vereshchagin Jun 30 '15 at 04:57
  • 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
12

You could also use negative numbers, like :

history -1

Or use a range (last 10):

history -1 -11 
robertrv
  • 129
  • 1
  • 2
5

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)

Alexey K.
  • 51
  • 1
  • 2
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]