Bash history with timestamp

Very often we are working on shared environments. And very often we are hearing “It wasn’t me…” when we are trying to identify who executed what.

We can get list of logged users from the last command, but how to linked these outputs with the list of commands from history? And/or how to push all commands to be written in history when users are using tmux or screen?

For me the easiest way was following sh script pushing setting in /etc/profile.d/bash_history.sh

# Add timestamp to history YYYY-MM-DD HH:MM
HISTTIMEFORMAT="%Y-%m-%d %T "

# To avoid duplicates
# export HISTCONTROL=ignoredups:erasedups

# Append to history file, not overwrite
shopt -s histappend

# Update the history file after each command and re-read it
export PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND$'\n'}history -a; history -c; history -r"

I think the comments are self-explaining. 
Adding timestamp, avoiding duplicates, appending history and immediately update the history.

No need to set X attribute to the file – it will be executed automatically after each login and the output looks like this:

1533 2020-09-23 16:02:09 rsync -v -a -h --progress /data/www/ /backup/web/full/www/ --delete after
1534 2020-09-24 14:02:42 df -h
1535 2020-10-05 14:33:29 cd
1536 2020-10-05 14:33:35 htop
1537 2020-10-05 14:33:52 apt update && apt upgrade
1538 2020-10-05 16:25:11 mc
1539 2020-10-05 16:56:30 htop
1540 2020-10-06 11:28:55 history

BTW one last note to mention – when you enable the history timestamp it is going to be applied to all records already stored in history with the time and date of the first command after new setup. 

So it will looks like this

413 2020-10-06 12:32:30 docker ls
414 2020-10-06 12:32:30 docker ps
415 2020-10-06 12:32:30 history | grep docker
416 2020-10-06 12:32:30 tmux attach
417 2020-10-06 12:32:30 sudo -i
418 2020-10-06 12:32:30 su -
419 2020-10-06 12:32:32 history

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *