Ubuntu – get the commands from history executed in bash in the last 15 mins

bashcommand linehistory

I want to put in place a cron job that sends me notification about a particular command executed in the last 15 mins. I can get the history along with timestamp using export HISTTIMEFORMAT='%F %T', but I couldn't really figure out how to filter it according to commands executed in the last 15 min only. Can someone suggest me a way to do that?

Best Answer

It's easier if you use a different time format (which you can, since setting HISTTIMEFORMAT to any value is enough for bash to keep track of time). So, use the Unix timestamp, and the difference between now and then:

HISTTIMEFORMAT='%s ' history |  awk -v now=$(date +%s) '(now - $2) < 15*60'

date +%s is the current Unix timestamp, and the second column of history's output is the HISTTIMEFORMAT field, so this checks if the difference in seconds is less than 15 minutes.

However, if your intention is to monitor command usage, then this really isn't the way to go about it. Setup auditd instead (it can be configured to watch for command execution).