Ubuntu – How to remove command-line history from a specific time period

bashcommand linehistory

How can I remove command-line history over a specific time period?

Is it possible do so with only one command?

Best Answer

While it is possible to store the time at which a command was run, the history manipulation commands do not use time as a reference. Look up HISTTIMEFORMAT in man bash:

HISTTIMEFORMAT
      If  this  variable  is  set and not null, its value is used as a
      format string for strftime(3) to print the time stamp associated
      with  each  history  entry displayed by the history builtin.  If
      this variable is set, time stamps are  written  to  the  history
      file  so they may be preserved across shell sessions.  This uses
      the history comment character  to  distinguish  timestamps  from
      other history lines.

If you had set HISTTIMEFORMAT before you ran the commands you wanted to delete, your .bash_history would have lines like so:

$ tail -4 ~/.bash_history 
#1449955320
history
#1449955329
history -w

Then you could take advantage of the Unix timestamps to delete them, using awk, for example:

awk -F# -v end=$(date -d yesterday +%s) \
  -v start=$(date -d 'now - 3 days' +%s) \
  '$2 < start || $2 > end {print; getline; print}'

I'm not sure how this command will work with multi-line commands, but you could maybe count the timestamps to get the number assigned to a command, and then use history to delete it.


If you hadn't set HISTTIMEFORMAT beforehand, then you'll have to do this manually.