Skip to content

Instantly share code, notes, and snippets.

@markizano
Created July 20, 2022 17:07
Show Gist options
  • Save markizano/f1f7d58d1147c10831f1547813b4a1db to your computer and use it in GitHub Desktop.
Save markizano/f1f7d58d1147c10831f1547813b4a1db to your computer and use it in GitHub Desktop.
bashrc snippet to preserve history across sessions since `HISTFILESIZE=-1` is unreliable.
export DATEFORMAT='%F/%R:%S';
export HISTCONTROL=ignoreboth
export HISTFILE=$HOME/.bash_history
export HISTFILESIZE=-1
export HISTSIZE=81920
export HISTTIMEFORMAT="$DATEFORMAT "
export HISTLOG=~/.bash_history.d
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:.:~/bin
export PROMPT_COMMAND='echo -en "\n\e[36m$?\e[0m; "; history -a; histlog "$(history 1)"'
# Place subsequent `histlog` command in ~/bin/histlog and it should take care of the rest.
#!/bin/bash
# @date: 2021-04-25
# @author: Markizano Draconus
# @description: I got sick and tired of my bash history dissapearing despite using
# HISTFILESIZE=-1, which disables truncating $HISTFILE
# This script created to export history commands to a sub-directory in my ~/.bash_history.d/
# folder to avoid my commands from getting truncated from my $HISTFILE.
# @usage: export PROMPT_COMMAND='histlog $(history 1)'
# Acquire the history files and directory...
export HISTLOG=${HISTLOG:-~/.bash_history.d}
export HISTLOGFILE="$HISTLOG/`date +%Y-%m`.bash_history"
# The last history item will be presented as the first argument.
# Since history operations are not available from scripts.
HISTLASTITEM="$1"
# Make sure directory exists.
test -d "$HISTLOG" || {
mkdir -p "$HISTLOG"
# ... and is owned by me.
test "$UID" -eq 0 && chown $SUDO_UID:$SUDO_GID "$HISTLOG"
}
# Strip the leading spaces, index number so we get $date: $command
histItem=`echo "$HISTLASTITEM" | perl -pe 's/^\s*\d+\s+//'`
# If I am just pressing [Enter] and no command was run,
test -e "$HISTLOGFILE" && {
# Don't append the previous command again to the log.
lastItem=`tail -n1 "$HISTLOGFILE"`
test "$histItem" == "$lastItem" && exit 0
}
# Append the history command.
echo "$histItem" >> "$HISTLOGFILE"
# Make sure the history file is owned by me.
test "$UID" -eq 0 && chown $SUDO_UID:$SUDO_GID "$HISTLOGFILE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment