Prune Bash History at Login

Prune Bash History at Login

You can use code based on the following to prune your bash shell command history whenever you log in. This eliminates duplicate commands, which slightly improves performance and can make history easier to use.

I originally described this approach here:

I had tried to modify that to merge history files from multiple machines:

After moving from WSL (Windows Subsystem for Linux) to Fedora, something wasn't working correctly, and I no longer needed history from multiple machines, so I had gemeni make some suggestions.

You can add these commands directly to ~/.bashrc or a script that it sources, or you can update one of those files to source this script, which you can keep as a separate script to source (not execute - HISTFILE might be different and history -r should run in the current shell).

This is how it works:

The hb uses bat to view the history with some formatting.

shopt -s histappend

export HISTCONTROL=ignoreboth
export HISTSIZE=10000
export HISTFILESIZE=10000

HISTFILE="$HOME/.bash_history"

if [[ -z "$HISTFILE" || ! -f "$HISTFILE" ]]; then
    echo "Error: HISTFILE is not defined or does not exist. Cannot clean history." >&2
    return 1
fi

temphist=$(mktemp)

nl "$HISTFILE" \
    | sort -f -b -k2 -r \
    | sed 's/[[:blank:]]*$//' \
    | sort -f -b -k2 -r -u \
    | sort -n \
    | cut -c8- \
    | sed 's/^[[:space:]]*//; s/[[:space:]]*$//; /\([^[:space:]]\{1\}.*\)\{8\}/!d' > "$temphist"
mv "$temphist" "$HISTFILE"
history -r
alias hb='history | tac | bat -l sh'