Today I finally decide to make a script to keep my bash_history synchronized among all the machines I use. It’s a simple script that retrieves all the .bash_history
files from all my machines, merges all the files into one, sort it, removes the duplicated lines and write it back to all the machines. The only drawback is that the original ordering of the history files is lost due to the alphabetical sorting step (needed to remove the duplicated lines).
WARNING: Make sure that your history file size limit is big enough to hold all the combined history files. Otherwise you’ll lose some of the entries. You can go to this post for reference on how to change the history file limits
Here’s the script:
echo copying local history file
history -a
cp .bash_history full_history
HOSTS="machine1.example.com machine2.example.com"
for i in $HOSTS; do
echo copying history file from $i
scp $i:~/.bash_history tmp_history.txt
cat tmp_history.txt >>full_history
wc -l tmp_history.txt
wc -l full_history
done
echo sorting the new history file and removing duplicates
sort full_history|uniq >uniq_history
rm full_history
echo replacing history file with the new one
mv uniq_history .bash_history
echo reloading bash history from file
history -c
history -r
wc -l .bash_history
for i in $HOSTS; do
echo backing up .bash_history in $i
DATE=\`date '+%Y%m%d%H%M%S'\`
ssh $i "cp <sub>/.bash_history</sub>/.bash_history$DATE"
echo replacing .bash_history in $i
scp .bash_history $i:~/.bash_history
done
The code is also available as a gist