Copier un fichier avant de la modifier (sauvegarde de sécurité / de travail)

#! /bin/bash
# [[safeedit]] backup the file, then edit it with your favorite editor
# Required:  ruby, saveback.rb
# 
# Author:
# Fred Radeff (FR), radeff@akademia.ch, radeff.red
# History: 28 janvier 2007  : FR, created
# No Copyright, steal this!
#########
#adapt this to you preference

editeur="/usr/bin/quanta"
#editeur="/usr/bin/gedit"
#editeur="/usr/bin/xemacs"
file=$*
saveback.rb $file
$editeur $file &

plus simple encore:

#!/bin/bash -f
FILENAME=$1
TIMEDATE=$(date +'%Y%m%d%k%M')
cp $1 $1"."$TIMEDATE

saveback.rb

#!/usr/bin/env ruby
#  script to backup a file
# Required:  ruby
# Source: Lucas CARLSON & Leonard RICHARDSON, Ruby cookbook, O'Reilly, 1st Ed., 2006 
# Fred Radeff (aka FR), radeff@akademia.ch, radeff.red, modified 2007.01.28 09h01

require 'ftools'

#versioning file
class File
def File.versioned_filename(base, first_suffix='.00')
  suffix = nil
  filename = base
  while File.exists?(filename)
	suffix = (suffix ? suffix.succ : first_suffix)
	filename = base + suffix
  end
  return filename
 end
end

#create backup
class File
def File.to_backup(filename, move=false)
  new_filename = nil
  if File.exists? filename
	new_filename = File.versioned_filename(filename)
	File.send(move ? :move : :copy, filename, new_filename)
  end
  return new_filename
 end
end


#interaction

## old
#puts "Enter the file to backup:"
#name = gets.chomp
#better to use directly the command-line argument, which is an array

name=ARGV[0]
newname=File.versioned_filename(name)
File.to_backup(name)
puts "Ok, " +name +" backup = " +newname

#test purposes
#100.times do |i|
#	name = File.versioned_filename('z.txt')
#	open(name, 'w') { |f| f << "Contents for run #{i}" }
#	puts "Created #{name}"
#end
#exit
  • info/safeedit.txt
  • Dernière modification: 2018/07/18 09:46
  • par radeff