Difference between revisions of "Esercizio 3 Prova Pratica 25-09-2014"

From Sistemi Operativi
Jump to navigation Jump to search
 
Line 99: Line 99:
 
for file in entries: olderVersion( new, file )
 
for file in entries: olderVersion( new, file )
  
entries = [ x for x in os.listdir('.') if os.path.isfile(x)]
+
if new+'.2' in entries:
if new+'.3' in entries:
 
 
     if filecmp.cmp(new+'.3', new+'.1'): os.link(new, new+'.2')
 
     if filecmp.cmp(new+'.3', new+'.1'): os.link(new, new+'.2')
 
     else: os.rename(new+'.1', new+'.2')
 
     else: os.rename(new+'.1', new+'.2')

Latest revision as of 10:02, 12 May 2015

Scrivere un programma python o uno scrip bash che faccia un backup storico di un file.
backn file n
deve mantenere n versioni del file specificato. n>2
Esempio:
backn miofile 10
se esiste miofile.9 deve essere rinominato in miofile.10
se esiste miofile 8 deve essere rinominato in miofile 9
e cosi' via fino a miofile.2, rinominato miofile 3.
ora se miofile.1 ha lo stesso contenuto di miofile.3, miofile diventa un link fisico a miofile.2
miofile viene copiato in miofile.1

Soluzione di Blissett

#! /bin/bash

if [[ $# != 2 || ! -f $1 ]]
then 
		echo "Usage: $0 file n_backup"
		exit -48
fi

file=$1
n_backup=$2
cartella="cartellaBackup"
true=0 

if [[ ! -d $cartella ]]
then
	mkdir $cartella
fi
cd ./$cartella

for i in `find ./ -name "$file*" | sort -n -r -t. -k3 | cut -d. -f3` 
do
	true=1
	tmp=`find ./ -name "$file.$i"`
	num=$(($i+1))
	mv $tmp "$file.$num"
	if [[ $num -gt n_backup ]]
	then
		rm "$file.$num"
	fi
done

if [[ $true -eq 1 ]]
then
	cmp -s "$file.2" "../$file"
	if [[ $? -eq 0 ]]
	then	
	echo creo link fisico.
		ln "$file.2" "$file.1"
	else
		cp ../$file ./
		mv $file "$file.1"
	fi
else
		cp ../$file ./
		mv $file "$file.1"
fi

--Blissett (talk) 13:14, 11 May 2015 (CEST)

Soluzione di Maldus

import argparse
import sys
import os
import shutil
import filecmp

def olderVersion( new, old ):
    new = new + '.'
    l = len(new)
    if new in old:
        try:
            num=int(old[l:])
            if num < args.version and num!=1 : os.rename(old, old[:l]+str(num+1))
        except ValueError:
            return 


parser = argparse.ArgumentParser(description='backup storico')
parser.add_argument('file', metavar='file', type=str, help='file di cui fare backup')
parser.add_argument('version', metavar='versione', type=int, help='numero di versione')
args = parser.parse_args()
new = args.file 

if args.version < 2:
    print("la versione deve essere > 2")
    sys.exit(1)

entries = [ x for x in os.listdir('.') if os.path.isfile(x)]
if not new in entries:
    print("Nessun file con quel nome")
    sys.exit(1)

for file in entries: olderVersion( new, file )

if new+'.2' in entries:
    if filecmp.cmp(new+'.3', new+'.1'): os.link(new, new+'.2')
    else: os.rename(new+'.1', new+'.2')
elif new+'.1' in entries: os.rename(new+'.1', new+'.2')

shutil.copyfile(new, new+'.1')