How to properly protect .bash_history against truncation?
7
votes
3
answers
1127
views
What can I do so that my
.bash_history
is only aver appended to?
I am working in a lot of environments, like singularity
, apptainer
, docker
, podman
and ssh with various settings and mounts. Each of the environments may have different HISTFILESIZE
value, there might be something in /etc/profile.d on different machines, and I have my own HISTFILE=.bash_historymy
HISTFILESIZE=""
HISTSIZE=""
set in my ~/.bashrc
and ~/.profile
and ~/.bash_profile
.
The problem is, if _one_ of the environments happens to set HISTFILESIZE
, bam - my .bash_history is lost. I am setting my own HISTFILESIZE
in my .bashrc
, but if I happen to source /nfs/my/friends/.profile
or other scripts they will override HISTFILESIZE
and not touch HISTFILE
, so still my separate HISTFILE
will be truncated. Once it happens, I lose my history. This has happened to me many times throughout the years on various systems and environments.
What I had, for quite some time, is a script in ~/.bashrc
that would create a number of .bash_history backups and rotate them, this was accompanied with some size checking, like:
name="$(basename "$HISTFILE")"
backupdir=~/.cache/bash_history/
mkdir -p "$backupdir"
file="$HISTFILE"
for ((i=1;i<5;++i)); do
cp "$file" "$backupdir/$name.$i"
file="$backupdir/$name.$i"
done
So I would have 5 "sessions" to restore the history file or backup it or "cat" it together.
I feel like this was an unsatisfactory temporary solution. Is there a proper solution to protect against bash truncating .bash_history? I would imagine one could run "diff" against old and new one and only merge the missed chunks from the back of .bash_history. I do not think making .bash_history
a fifo is a good solution. For example, I would be happy if a shell would "restore" the lost truncated commands on the next ~/.bashrc
run from a backup file.
Asked by KamilCuk
(970 rep)
Mar 14, 2025, 11:34 AM
Last activity: Mar 14, 2025, 08:33 PM
Last activity: Mar 14, 2025, 08:33 PM