3

Is there a way to view the time/date the last command was entered into the terminal?

I know I can just use the up key, or type history to see a list of previous commands, but is there any way to get a time stamp for them?

5

I tried this and it seemed to work:

$ echo 'export HISTTIMEFORMAT="%d/%m/%y %T "' >> ~/.bashrc
$ source ~/.bashrc

OR (if you only want once off)

$ HISTTIMEFORMAT="%d/%m/%y %T

followed by

history

3

You can use history with timestamp as indicated in another answer to get previous execution that way.

You may consider modifying your prompt to display a time stamp in the terminal,so it can read from a log or scrollback. the quickest way to get it in the current shell

export PS1="(\d \t)$PS1"

to add a timestamp prefix to your prompt

(Thu Aug 3 20:03:29)$

You can modify your .bashrc to add a timestamp to the prompt with every login.

minor note - timestamp is printed when prompt is printed, if a user waits a long time before executing a command the time may not correspond, i.e. this is useful for logging but not security audit.


Details

The variable that configures the terminal prompt is PS1, open ~/.bashrc in any editor and locate the line starting with PS1=, there you will likely see some combination of undecipherable characters these are color codes to set colors for portions of the terminal.

Here is an example from the default rpi one

if [ "$color_prompt" = yes ]; then
  PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:[\033[01;34m\]\w \$\[\033[00m\] '
else
  PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi

The key line here is the this tidbit \u@\h:\w which makes the terminal prompt display USER@HOST:/current/wd/

There are several other variables that can be used in PS1, here is a curated selection of relevant ones

\d   The date, in "Weekday Month Date" format (e.g., "Tue May 26"). 
\t   The time, in 24-hour HH:MM:SS format. 
\T   The time, in 12-hour HH:MM:SS format. 
\@   The time, in 12-hour am/pm format. 

So if we add instances (\d \t) as such:

# color
PS1='${debian_chroot:+($debian_chroot)}(\d \t)\[\033[01;32m\]\u@\h\[\033[00m\]:[\033[01;34m\]\w \$\[\033[00m\]
# no color
PS1='${debian_chroot:+($debian_chroot)}(\d \t)\u@\h:\w\$ '

PS1 then the displayed prompt would read

(Thu Aug 3 20:03:29)USER@HOST:/current/wd/

There are other substitutions you can use, because PS1 is a bash variable, if you would prefer to use a unix-timestamp you may instead use command substitution and use $(date +%s) as such

# no color
PS1='${debian_chroot:+($debian_chroot)}($(date +%s))\u@\h:\w\$ '

To display a prompt like

(1501784711)USER@HOST:/current/directory

You can use any terminal command or shell script you choose to add text/info to your prompt this way.

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.