Skip to content

Instantly share code, notes, and snippets.

@edgardleal
Last active May 31, 2017 19:17
Show Gist options
  • Save edgardleal/d0356ed94422cb33f7d66bc2daeda331 to your computer and use it in GitHub Desktop.
Save edgardleal/d0356ed94422cb33f7d66bc2daeda331 to your computer and use it in GitHub Desktop.
Backup bash or zshell history shell to not lost any command
#!/bin/bash -
#title :backup_history.sh
#description :This script will make a backup of bash history.
#author :Edgard Leal <[email protected]>
#date :20160221
#version :0.3
#usage :bash backup_history.sh
#notes :
#bash_version :4.1.5(1)-release
#==============================================================================
declare -r KEEP=200
declare BASH_HIST
# you can use for zshell
# ./backup_history.sh "~/.zsh_history"
#
if [ -z "$1" ]; then
if [ -f "~/.zsh_history" ]; then
BASH_HIST=~/.zsh_history
else
BASH_HIST=~/.bash_history
fi
else
BASH_HIST="$1"
fi
declare -r BACKUP=$BASH_HIST.$(date +%y%m)
declare -r current_size="$(wc -l $BASH_HIST | awk '{print $1}')"
echo $current_size
if [ -s "$BASH_HIST" -a "$BASH_HIST" -nt "$BACKUP" ]; then # history file is newer then backup
if [[ "$current_size" -gt "3000" ]]; then # there is already a backup
mv -f $BASH_HIST $BACKUP
tail -n$KEEP $BACKUP > $BASH_HIST
history -r
else # create new backup, leave last few commands and reinitialize
echo "Bash history is to short to create a bakup"
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment