Tuesday, April 18, 2017

Bash history backup

I like my bash history, and I proudly have this in my .bash_profile:

# Increase bash history size, append instead of overwrite history on exit export HISTSIZE=10000000 export HISTCONTROL=erasedups shopt -s histappend

However, after reading about Historian I realised I have no backup. Instead of installing Historian, I decided to take a simpler approach. Here it is:

#!/bin/bash set -euo pipefail IFS=$'\n\t' # # Makes a daily backup of your .bash_history, keeps the last 2 backups. # BACKUPDIR="${HOME}/.bash_history_backup" mkdir -p "${BACKUPDIR}" cp ${HOME}/.bash_history "${BACKUPDIR}/bash_history_$(date +%Y%m%d)" for h in $(ls -1r "${BACKUPDIR}"/bash_history_* | tail -n +3); do rm $h; done

Put the above contents in a file somewhere, e.g. in ~/bin/bash_history_backup.sh and activate it with:

ln -s ~/bin/bash_history_backup.sh /etc/cron.daily/
or add the following line with the more cumbersome route through crontab -e:
0 0 * * * $HOME/bin/bash_history_backup.sh

Update 2017-04-22: The script actually works now :)

Update 2017-04-23: The script actually actually works now :)