Last active
November 10, 2023 21:36
-
-
Save zcutlip/1be43a44f3b5b00674c56081effb67c7 to your computer and use it in GitHub Desktop.
Shell history backup function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# shellcheck shell=bash | |
# shellcheck disable=SC1091 | |
# source from .zshrc or similar: | |
# source "$DOTFILES/shell_history_backup.zsh" && _backup_shell_hist | |
function _backup_shell_hist(){ | |
if [ -n "$SHELL_HIST_BACKUP_LOC" ] | |
then | |
_histfile_base="$(basename "$HISTFILE")" | |
# .zsh_history_2023-09-14 | |
_current="$_histfile_base"_"$(date -u +"%Y-%m-%d")" | |
_fq_current="$SHELL_HIST_BACKUP_LOC/$_current" | |
if [ -f "$_fq_current" ]; | |
then | |
# no need to backup if we've backed up recently | |
return 0 | |
fi | |
mkdir -p "$SHELL_HIST_BACKUP_LOC" | |
# list all history backups, sort descending by time modified, grab the first, which is the newest | |
_fq_last="$(find "$SHELL_HIST_BACKUP_LOC" -name "$_histfile_base"_\* -print0 | xargs -0 ls -t | head -n 1)" | |
_last_size=0 | |
# copy the live history file to today's backup | |
if ! cp "$HISTFILE" "$_fq_current"; | |
then | |
echo "*****************************************" >&2 | |
echo "!! WARNING: shell history backup failed!!" >&2 | |
echo "*****************************************" >&2 | |
return 1 | |
fi | |
# filesize is a shell function defined elsewhere | |
# it essentially does stat -f"%z" <filename> | |
_current_size="$(filesize "$_fq_current")" || return | |
# if there was at least one existing backup, compare its size to today's size | |
if [ -n "$_fq_last" ]; | |
then | |
_last_size="$(filesize "$_fq_last")" || return | |
# shell history size should only grow | |
# so if today's backup is smaller than the previous | |
# then we have a problem | |
if [ "$_current_size" -lt "$_last_size" ]; | |
then | |
echo "**************************************************" >&2 | |
echo "!! WARNING: '$HISTFILE' appears to be truncated !!" >&2 | |
echo "**************************************************" >&2 | |
fi | |
fi | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment