Bash – Simplest standard way to print last bash command with timestamp

bashcommand history

I would like to print last bash command with its timestamp. history 1 shows the history command itself. I need to use it on many machines, so it should not depend on any custom configuration. There surely must be some simple command that I am missing to do this, like lastcmd or something 🙂

Note that fc -l -1 shows the last command but without timestamp, and is too complicated to type it frequently anyway.

Just to clarify, I am looking for some standard and simple way to do this because I need to use it on many servers and it is not feasible to customize them all or create custom functions. Also I need to type this command manually so it should be really simple.

It seems that HISTCONTROL=ignoreboth is a default setting on servers I need to access so I can use:

 history 1 

(history command prefixed with a space) which does not put it in the history, so it correctly shows the last command.

HISTTIMEFORMAT is not set by default though, so it is not a complete solution. Is there a simpler way?

Best Answer

As you point out, history 1 prints the history command itself since that is the last command you ran. To get the previous one, you'd need history 2:

$ touch foo
$ history 2
$ history 2
19950  touch foo
19951  history 2

So, to get the previous command without counting history itself, pass it through head -n1:

$ history 2 | head -n1
19952  touch foo

Then, add the time stamp in whatever format you want (see man 3 strftime for available formats):

$ HISTTIMEFORMAT="%F %H:%m:%S " history 2 | head -n1
19959  2016-06-11 15:06:08 touch foo