I know that Bash has both HISTSIZE and HISTFILESIZE variables that control how long history is saved for, and how much of it is saved. I would like to keep an archive of my history. However, if I set either of the two variables mentioned above to a very large number, it makes searching for old commands very difficult, and after enough time they might get deleted anyway.

How can I automatically archive my bash history files once they get to a certain size, and is this method applicable to other log files (such as /var/log/auth.log)?

# This script creates monthly backups of the bash history file. Make sure you have
# HISTSIZE set to large number (more than number of commands you can type in every
# month). It keeps last 200 commands when it "rotates" history file every month.
# Typical usage in a bash profile:
# HISTSIZE=90000
# source ~/bin/history-backup
# And to search whole history use:
# grep xyz -h --color ~/.bash_history.*

BACKUP=$BASH_HIST.$(date +%y%m)

if [ -s "$BASH_HIST" -a "$BASH_HIST" -nt "$BACKUP" ]; then
  # history file is newer then backup
  if [[ -f $BACKUP ]]; then
    # there is already a backup
    cp -f $BASH_HIST $BACKUP
    # create new backup, leave last few commands and reinitialize
    mv -f $BASH_HIST $BACKUP
    tail -n$KEEP $BACKUP > $BASH_HIST
    history -r

Taken from Never lost your bash history again on "https://lukas.zapletalovi.com".

| improve this answer | |

There is a bash script recommendation here

| improve this answer | |

To answer your second question first:

The Ubuntu log files are already processed by logrotate to keep them managable and within size limits.

You can possibly even "abuse" it for your history files, it is quite convenient.

| improve this answer | |

This solution saves with date-time of execution:

mkdir ~/.logs

add this to your .bashrc or .bash_profile:

export PROMPT_COMMAND='if [ "$(id -u)" -ne 0 ]; then echo "$(date "+%Y-%m-%d.%H:%M:%S") $(pwd) $(history 1)" >> ~/.logs/bash-history-$(date "+%Y-%m-%d").log; fi'

to search in history type:

grep -h logcat ~/.logs/bash-history-2016-04*

taken from https://spin.atomicobject.com/2016/05/28/log-bash-history/

| improve this answer | |
  • What if PROMPT_COMMAND already contains something? Wouldn't it be safer to concatenate your command with it instead? Maybe something like export PROMPT_COMMAND=$"$PROMPT_COMMAND\n <your code>" would do. – Jacajack May 16 '18 at 12:36
  • my PROMPT_COMMAND already had something. so I assigned it to a variable prompt_command and after export command, I do export PROMPT_COMMAND="prompt_command;$PROMPT_COMMAND" – nurp Jun 22 '18 at 7:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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