How can I automatically rotate/archive my bash history logs?

Solution 1:

#!/bin/sh
# 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.*
#

KEEP=200
BASH_HIST=~/.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
  else
    # create new backup, leave last few commands and reinitialize
    mv -f $BASH_HIST $BACKUP
    tail -n$KEEP $BACKUP > $BASH_HIST
    history -r
  fi
fi

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

Solution 2:

You can use logrotate to backup your ~/.bash_history file.

Create a config file for logrotate in /etc/logrotate.d/bash_history.

/home/YOUR_USERNAME/.bash_history {
    weekly
    missingok
    rotate 5
    size 5000k
    nomail
    notifempty
    create 600 YOUR_USERNAME YOUR_USERNAME
}

You can check if it works using this command:

sudo logrotate --force /etc/logrotate.d/bash_history

To see the files:

ls ~/.bash_history*

I found it on this webpage https://kowalcj0.github.io/2019/05/13/logrotate-bash-history/

Solution 3:

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/

Solution 4:

There is a bash script recommendation here