3

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

Is it possible do so with only one command?

5
  • Are you just trying to ensure that someone after you cannot see what you have done? Dec 12, 2015 at 20:52
  • Basically, yes.
    – TellMeWhy
    Dec 12, 2015 at 20:53
  • I just edit ~/.bash_history and delete the lines I don't want left around. Dec 12, 2015 at 20:54
  • 2
    prepend your commands with a space. Eg enter ` gedit /etc/rc.local` Commands with a leading space do not get entered into history. Dec 12, 2015 at 20:57
  • 2
    The thing is, .bash_history doesn't store commands based on time periods. It just adds commands one by one. You're much better off simply deleting the whole file. It will be recreated next time shell starts Dec 12, 2015 at 20:59

1 Answer 1

3

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .