From d8074d971fe0a74402c4fc3858e698e76de3870d Mon Sep 17 00:00:00 2001 From: Brian Adkins Date: Thu, 23 Feb 2012 11:38:49 -0500 Subject: [PATCH] Added backup file rotation --- .gitignore | 1 + dedup_bash_history.rb | 37 ++++++++++++++++++++++++++++--------- 2 files changed, 29 insertions(+), 9 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b25c15b --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*~ diff --git a/dedup_bash_history.rb b/dedup_bash_history.rb index 34350f5..f7ab8ce 100755 --- a/dedup_bash_history.rb +++ b/dedup_bash_history.rb @@ -29,17 +29,36 @@ # ls # echo "hello -history_file = File.expand_path('~/.bash_history') -backup_file = File.expand_path('~/.bash_history_backup') -temp_file = File.expand_path('~/.bash_history_temp') +module DeDuper + NUM_BACKUP_FILES = 20 + HISTORY_FILE = File.expand_path('~/.bash_history') + BACKUP_FILE = File.expand_path('~/.bash_history_backup') + TEMP_FILE = File.expand_path('~/.bash_history_temp') -`cp #{history_file} #{backup_file}` + module_function -File.open(history_file, "r") do |hfile| - File.open(temp_file, "w") do |tfile| - hfile.readlines.reverse.uniq.reverse.each {|line| tfile.puts(line) } + def rotate_backup_files n + return if n < 1 + + if File.exist?(current_file = "#{BACKUP_FILE}#{n}") + `cp #{current_file} #{BACKUP_FILE}#{n+1}` + end + + rotate_backup_files(n-1) end -end -`mv #{temp_file} #{history_file}` + def run + rotate_backup_files(NUM_BACKUP_FILES) + `cp #{HISTORY_FILE} #{BACKUP_FILE}1` + + File.open(HISTORY_FILE, "r") do |hfile| + File.open(TEMP_FILE, "w") do |tfile| + hfile.readlines.reverse.uniq.reverse.each {|line| tfile.puts(line) } + end + end + + `mv #{TEMP_FILE} #{HISTORY_FILE}` + end +end +DeDuper.run