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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<span class='line'>echo copying local history file
</span><span class='line'>history -a
</span><span class='line'>cp .bash_history full_history
</span><span class='line'>
</span><span class='line'>HOSTS="machine1.example.com machine2.example.com"
</span><span class='line'>for i in $HOSTS; do
</span><span class='line'> echo copying history file from $i
</span><span class='line'> scp $i:~/.bash_history tmp_history.txt
</span><span class='line'> cat tmp_history.txt >>full_history
</span><span class='line'> wc -l tmp_history.txt
</span><span class='line'> wc -l full_history
</span><span class='line'>done
</span><span class='line'>
</span><span class='line'>
</span><span class='line'>echo sorting the new history file and removing duplicates
</span><span class='line'>sort full_history|uniq >uniq_history
</span><span class='line'>rm full_history
</span><span class='line'>
</span><span class='line'>echo replacing history file with the new one
</span><span class='line'>mv uniq_history .bash_history
</span><span class='line'>echo reloading bash history from file
</span><span class='line'>history -c
</span><span class='line'>history -r
</span><span class='line'>
</span><span class='line'>
</span><span class='line'>wc -l .bash_history
</span><span class='line'>
</span><span class='line'>
</span><span class='line'>for i in $HOSTS; do
</span><span class='line'> echo backing up .bash_history in $i
</span><span class='line'> DATE=`date '+%Y%m%d%H%M%S'`
</span><span class='line'> ssh $i "cp ~/.bash_history ~/.bash_history$DATE"
</span><span class='line'> echo replacing .bash_history in $i
</span><span class='line'> scp .bash_history $i:~/.bash_history
</span><span class='line'>done</span>
The code is also available as a gist
Posted by Ruben Laguna
May 30 th , 2007 12:00 am
bash , bash_history , bashrc , history , linux , merge , ssh , sync , synch , synchronize
« Google Experimental Search
Lions, buffalos and crocodiles »