1

When adding "HISTTIMEFORMAT" to bashrc, the timestamps of when a command was executed are made available when running the "history" command.

But the timestamps themselves are not saved to the bash_history file (atleast not in plain text).

I am looking for a solution that will write the timestamp to the file itself so that archived .bash_history files from various workstations can be viewed in an editor outside the userspace and still contain the timestamps of when commands were executed.

If the timestamps are being saved to the history file itself but just not viewable in an editor when opening the bash_history file, and it is still possible to view these timestamps by using the history command itself on a rogue bash history file, then that would also suffice.

Thanks

OB7DEV
  • 125
  • 8

3 Answers3

1

This is a example of bash history ( when using HISTTIMEFORMAT )

#1625963751
sleep 45 ; ssh proxy.lan

the number 1625963751 is the unix timestamp ( https://en.wikipedia.org/wiki/Unix_time ) .

if you are using linux , date has a option to display this date in human form .

em444$ date -d @1625963751
Sat Jul 10 20:35:51 EDT 2021
EchoMike444
  • 449
  • 1
  • 3
  • 6
  • How do I append the unix timestamp to each command in a bash file? When opening old bash historys I have, there is no #number above each command as there is in your example. Opening a bash_history file in vim just gives a list of commands. Each line is a command, there's no time stamps above each line. – OB7DEV Jul 18 '21 at 00:31
  • if you dont use HISTTIMEFORMAT , you will not have timestamp . – EchoMike444 Jul 18 '21 at 00:38
0

edit /etc/bashrc and add this line to the bottom:

PROMPT_COMMAND="echo `date +'%F %H:%M'` `whoami` `history|tail -1` >> ~/history.txt; $PROMPT_COMMAND"

I am not sure if you change ~ to root, \root\history.txt can be accessible to all users yet.

George Y
  • 528
  • 6
  • 16
  • \root\history.txt ??? – Gerard H. Pille Jul 18 '21 at 03:37
  • `~/history.txt` means the file `history.txt` in current user's home directory. `/root/history.txt` means the file in root directory. I assume you want to save historical commands to a specific file if you want a timestamp on each commands. – George Y Jul 18 '21 at 04:02
  • It's only that backslashes have a different meaning on unix. Apart from that, 'history -1' may be cheaper than piping through tail. – Gerard H. Pille Jul 18 '21 at 06:06
  • It seems I cannot get the history|tail -1 output appended to history.txt. The rest of the command works though. So my history.txt has date, user, but no command... – OB7DEV Jul 19 '21 at 21:35
0

export HISTTIMEFORMAT='(%Y-%m-%d) (%H:%M:%S) ' Try this line.

George Y
  • 528
  • 6
  • 16