3

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

Is it possible do so with only one command?

  • Are you just trying to ensure that someone after you cannot see what you have done? – Charles Green Dec 12 '15 at 20:52
  • Basically, yes. – TellMeWhy Dec 12 '15 at 20:53
  • I just edit ~/.bash_history and delete the lines I don't want left around. – Doug Smythies Dec 12 '15 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. – Charles Green Dec 12 '15 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 – Sergiy Kolodyazhnyy Dec 12 '15 at 20:59
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.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.