Search code examples
scriptingbackuphistorytcsh

How to backup tcsh history periodically to a single file in chronological manner?


I use tcsh at work - one of the features I use extensively is command-line history completion at the shell prompt. Currently, I've limited the size of my history file to 2000 (as I don't want to slow down the shell too much). However at times I need a command I know I've used a month or two back , but by now has been erased. So I want a system wherein:

  1. My history buffer stores 2000 lines only

  2. Instead of older commands getting erased , they should be saved into a "master" history file, ordered chronologically i.e if two shells were opened , then the commands entered in the history should be sorted as per the datestamp (not the order in which the shells were closed)!

  3. It would be perfect , if this master history file could be auto-backed up, say per week basis.

I'm sure many of avid shell users have faced a situation like this - I'm hoping to get the answer from one of such users !!


Solution

  • 2000 is pretty low. You could raise that a fair amount without suffering too much.

    Next you probably want to store the history on logout, since this is when new commands are added to the .history file.

    Create a file called .logout in your $HOME (for bash users, this file is .bash_logout). In this, copy the contents of the history to a permanent store. For example:

    cat $HOME/.history >> $HOME/.ancient_history
    

    This will append the history to a file ".ancient_history". For bash users, the file to copy is called .bash_history.

    Then create a cron job that creates a back up of this every now and again. For starters here is one that moves the file to a filename with a date stamp at 5 minutes past midnight every day.

     5 0 * * *       mv $HOME/.ancient_history $HOME/.ancient_history_`date +%s`
    

    There are probably more things you could do with this, but this is enough to get started. It's a pretty good idea that I hadn't thought of doing before either :-)