Automatische Sicherung (Beispiel): Unterschied zwischen den Versionen

Aus wiki.archlinux.de
 
(11 dazwischenliegende Versionen von 2 Benutzern werden nicht angezeigt)
Zeile 1: Zeile 1:
{{righttoc}}
Dies ist Beispiel und Anleitung für ein automatisches, rotierendes und inkrementelles Backup.
Dies ist Beispiel und Anleitung für ein automatisches, rotierendes und inkrementelles Backup.
Das hier verwendete Skript von Mike Rubbel baut auf dem [[rsync]] Befehl auf und sichert die Daten von /home.
Das hier verwendete Skript (Original von Mike Rubbel im Anhang) baut auf dem [[rsync]] Befehl auf und sichert die Daten  
[[Systemd/Timers]] werden genutzt um das Backup täglich, wöchentlich und monatlich automatisch vorzunehmen.
täglich, wöchentlich und monatlich. Hierzu wird ein [[Systemd/Timers | Systemd-Timer]] genutzt.
 
Das original Skript entstand 2004 und fand so viel Anklang, dass es in Perl übersetzt wurde und als [[rsnapshot]] Einzug in den Befehlspool von Linux hielt.
Das Skript entstand 2004 und fand so viel Anklang, dass es in Perl übersetzt wurde und als [[rsnapshot]] Einzug in den Befehlspool von Linux hielt.
Wer den Befehl diesem Skript vorzieht, kann auch diesen benutzen. Das Endergebnis dürfte jedoch gleich sein da beide rsync zum Speichern der Dateien einsetzen.
Wer den Befehl diesem Skript vorzieht, kann auch diesen benutzen. Das Endergebnis dürfte jedoch gleich sein da beide rsync zum Speichern der Dateien einsetzen.


{{Hinweis|Da die Sicherung auf einer lokalen Festplatte stattfindet, kann sie weder bei Feuer noch bei einem Einbruch vor Datenverlust schützen.
{{Hinweis|Da die Sicherung auf einer lokalen Festplatte stattfindet, kann sie weder bei Feuer noch bei einem Einbruch vor Datenverlust schützen.}}
Auch wenn bislang Schädlinge mit Administrationsrechten auf Linux sehr unwahrscheinlich sind, muss hier auf diese Gefahr hingewiesen werden.}}


Als Backup im privaten Bereich leistet es aber gute Dienste.
Durch das automatische Sichern stellen Festplattendefekte und versehentliches Löschen keine Gefahr mehr da.
Durch das automatische Sichern stellen Festplattendefekte und versehentliches Löschen keine Gefahr mehr da.
Durch das rotierende Verfahren hat man die Möglichkeit, auf mehrere gesicherte Dateiversionen zuzugreifen.
Durch das rotierende Verfahren hat man die Möglichkeit, auf mehrere gesicherte Dateiversionen zuzugreifen.
Trotzdem bleibt die Datenmenge gering. Rsync speichert die Daten jeweils nur einmal physisch ab und erstellt die einzelnen Schichten mittels Hardlinks.
Trotzdem bleibt die Datenmenge gering. Rsync speichert die Daten jeweils nur einmal physisch ab und erstellt die einzelnen Schichten mittels Hardlinks.
Da die Daten nur ein mal kopiert werden, ist die Geschwindigkeit des backups hervorragend.
Da immer nur die jeweils veränderten Daten neu gesichert werden, ist die Geschwindigkeit des backups hervorragend.


== Anleitung ==
== Anleitung ==
Zeile 20: Zeile 16:
=== Die Sicherungs-Festplatte ===
=== Die Sicherungs-Festplatte ===
Der Sicherungs-Datenträger sollte fest in den Rechner verbaut werden.
Der Sicherungs-Datenträger sollte fest in den Rechner verbaut werden.
Der Datenträger sollte ausreichent groß sein. Als Format eignet sich ext4. Fat Systeme unterstützen keine Hardlinks.
Der Datenträger muss ausreichend groß sein. Die folgenden Schritte sind als Beispiel zu verstehen:
Die folgenden Schritte sind als Beispiel zu verstehen. Auch kann statt der hier verwendeten Konsolenbefehlen zur Datenträgereinbindung, mit den GUI Programmen Gparted bzw. KDE Partitionsverwaltung gearbeitet werden.
 
====Partitionieren====
Der Datenträger wird wie in [[fdisk]] bzw. [[gdisk]] beschrieben mit 1. Partition versehen.
 
==== Formatieren ====
Als Format eignet sich ext4. Fat Systeme unterstützen keine Hardlinks.
mkfs.ext4 /dev/sdx1
 
====Datenträger Benennen ====
Der Datenträger erhält das Label SICHERUNG
e2label /dev/sdx1 SICHERUNG
 
==== Festplatte Einhängen ====
Ein Verzeichnis SICHERUNG auf root (/) anlegen
mkdir /SICHERUNG
 
====/etc/fstab====
öffnen mit
nano /etc/fstab
 
und hier folgendes einfügen:
/dev/sdx1 /SICHERUNG ext4 defaults 0 2
 
====mounten====
Das System Neustarten oder die Festplatte SICHERUNG auf /SICHERUNG ins Dateisystem einbinden.
mount /dev/sdx1 /SICHERUNG
 
=== Das Backup Skript ===
Falls auf dem System noch nicht vorhanden, wird jetzt rsync installiert.
pacman -S rsync
 
Das folgende Skript wird kopiert und als {{ic|snapshot.sh}} in {{ic|/usr/local/bin/}} abgespeichert. Mit einem {{ic|chmod a+rx /usr/local/bin/snapshot.sh}} wird es ausführbar gemacht.
 
Die ''CUSTOMIZING SECTION'' im Skript sollte auf die eigenen Gegebenheiten angepasst werden.


Für die Einbindung externer Sicherung-Datenträger gibt die Seite [[Rdiff-backup]] Anregung.
Die Datei {{ic|snapshot_exclude.txt}} wird ebenfalls kopiert und nach {{ic|/usr/local/bin/}} gespeichert.
Alle in der snapshot_exclude.txt gelisteten Dateien und Verzeichnisse werden von einer Sicherung ausgeschlossen.


=== Partitionieren ===
Danach kann mit folgendem Befehl die Funktion überprüft werden. Das Backup wird mit Rootrechten ausgeführt.
Zuerst schaut man, welche Festplatte man überhaupt Partitionieren will:
snapshot.sh


==== 1. Möglichkeit: fdisk ====
Bein ersten Durchlauf werden alle Daten nach daily.0 kopiert. Bei einem erneuten Aufruf des Befehls wird daily.0 nach daily.1 kopiert. Danach wird die daily.0 mit dem aktuellen Stand aktualisiert. Bei der Angabe von DAYS=6 in der ''CUSTOMIZING SECTION''; wird die spätere 7. Sicherung entweder als erste wöchentliche Sicherung umbenannt oder gelöscht, bevor die Sicherungen daily.5 bis daily.1 jeweils einen Zähler aufrücken.


  $ sudo fdisk -l     # listet alle Datenträger auf. Hier muss man sich den betreffenden Laufwerksbuchstaben einprägen.
Das Skript
  <nowiki>#!/bin/bash
##
##      Script: snapshot.sh
##
##      Creates daily, weekly and montly hardlink backupslices with rsync.
##
##      Version: 0.4
##
##      Original from:  Mike Rubel (http://www.mikerubel.org/computers/rsync_snapshots/)
##
##     License:  LGPL
##
##      Disclaimer: Use this software on your own risk, it works for me but there are no guaranties at all.
##
##      Changes from tuxnix:        *Only one systemd timer needed
##                                  *rsync.log
##                                  *Source directory choosable
##                                 
##                                             
##
## ======================= CUSTOMIZING SECTION ========================


Alternativ kann {{ic|lsblk}} verwendet werden:
SOURCE='/NAS/  /home/tuxnix/'                        # Source needs a / at the end. More then only one SOURCE-Directories are possible (set ' ' marks).
EXCLUDES=/usr/local/bin/snapshot_exclude.txt        # full path of exludefile is needed


$ lsblk
MOUNT_RO=true                                        # For remount with write protection set to true
MOUNT_DEVICE=/dev/disk/by-label/SICHERUNG            # Taget device
MOUNT_POINT=/SICHERUNG                              # Mount point of target device
TARGET=/SICHERUNG                                    # Target directory - full directory path of mounted device is needed


Bei den folgenden Befehl muss jeweils das X durch den Laufwerksbuchstaben der Sicherung-Festplatte ersetzt werden.
CHECK_HDMINFREE=true;        # Check free space
HDMINFREE=98;                # Make a backup up to this percentage


Falls man mit den Vorschlägen zufrieden ist, einfach die {{ic|Enter-Taste}} drücken drücken.
DAYS=6;                      # Number of daily backups -1
WEEKS=3;                      # Number of weekly backups -1
MONTHS=11;                    # Number of monthly backups -1


Gegebenfalls {{ic|J}} oder {{ic|n}} eingeben, wenn dies erforderlich ist.
$ sudo fdisk /dev/sdX
  m      # listet alle Optionen auf
  d      # löscht provisorisch eine Partition. Bitte solange wiederholen bis alle vorhandenen Partitionen gelöscht sind.
  n      # Erstellt provisorisch eine neue Partition


Nun müssen alle Änderungen durch das Betätigen von {{ic|w}} gespeichert werden.
# ---------------------- Check -----------------------------------------------------------------------------------------


''ACHTUNG'': Danach werden ''alle'' Daten auf der Festplatte ''überschrieben''!
# Make sure we're running as root
if (( `id -u` != 0 )); then { echo "Sorry, must be root.  Exiting..."; exit; } fi


  w
# Check exludefile exists
if ! [ -f $EXCLUDES ] ; then { echo "Error: Exclude File $EXCLUDES missing"; exit; } fi


(Sollte man sich einmal verlaufen haben, kann man mit q jederzeit den fdisk Befehl abbrechen.)


==== 2. Möglichkeit gdisk ====
# Remount Device rw
Auch hier müssen wir zuerst schauen, welche Festplatte überhaupt partitioniert werden soll.
if $MOUNT_RO ; then
        mount -o remount,rw $MOUNT_DEVICE $MOUNT_POINT
        if (( $? )) ; then
            echo "Error: could not remount $MOUNT_DEVICE readwriteable"
            exit
        fi
fi
 
# Check free space on disk
GETPERCENTAGE='s/.* \([0-9]\{1,3\}\)%.*/\1/'
if $CHECK_HDMINFREE ; then
        KBISFREE=`df /$TARGET | tail -n1 | sed -e "$GETPERCENTAGE"`
        if [ $KBISFREE -ge $HDMINFREE ] ; then
                echo "Error: Not enough space left for rotating backups!"
                logger "Error: Not enough space left for rotating backups!"
                exit
        fi
fi
 
# Give Source some time to wake up if needed.
ls $SOURCE > /dev/null
if (( $? )) ; then
    echo "Wait 10 seconds till $SOURCE device is arrivable."
    sleep 10
    ls $SOURCE > /dev/null
    if (( $? )); then
    echo "Can't read $SOURCE"
    exit
    fi
fi
 
# ---------------Rotate Monthly Snapshots------------------------------------------------------------------------------
 
if [ -d $TARGET/weekly.$WEEKS ] && ! [ -d $TARGET/monthly.0 ] ; then
 
    echo "mv $TARGET/weekly.$WEEKS $TARGET/monthly.0"
    mv $TARGET/weekly.$WEEKS $TARGET/monthly.0
 
elif [ -d $TARGET/weekly.$WEEKS ] && [ -d $TARGET/monthly.0 ] ; then
 
    STAMP_0=`stat -c %Y $TARGET/weekly.$WEEKS`
    STAMP_1=`stat -c %Y $TARGET/monthly.0`
 
    if [ $(( ($STAMP_0 - $STAMP_1)/(60*60*24) )) -ge 30 ] ; then
 
          echo ""
          echo "Rotate Monthly Snapshots:"
 
# Step 1: Delete the oldest monthly snapshot, if it exists
          if [ -d $TARGET/monthly.$MONTHS ] ; then
                echo "rm -rf $TARGET/monthly.$MONTHS"
                rm -rf $TARGET/monthly.$MONTHS
          fi
 
# Step 2: Shift the middle snapshots by one
          OLD=$MONTHS
          while [ $OLD -ge 1 ] ; do
                OLD=$[$OLD-1]
                if [ -d $TARGET/monthly.$OLD ] ; then
                        NEW=$[ $OLD + 1 ]
                        echo "mv $TARGET/monthly.$OLD $TARGET/monthly.$NEW"
                        mv $TARGET/monthly.$OLD $TARGET/monthly.$NEW
                fi
          done
 
# Step 3: move oldest weekly to monthly.0
            echo "mv $TARGET/weekly.$WEEKS $TARGET/monthly.0"
            mv $TARGET/weekly.$WEEKS $TARGET/monthly.0
         
    fi
fi


lsblk
# ---------------Rotate Weekly Snapshots------------------------------------------------------------------------------


liefert beispielsweise
if [ -d $TARGET/daily.$DAYS ] && ! [ -d $TARGET/weekly.0 ] ; then


NAME    MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
    echo "mv $TARGET/daily.$DAYS $TARGET/weekly.0"
sda      8:0    0  1,8T  0 disk
     mv $TARGET/daily.$DAYS $TARGET/weekly.0
├─sda1    8:1    0 886,5G  0 part
└─sda2    8:2    0 976,6G  0 part /windows
sdb      8:16  0 465,8G  0 disk
├─sdb1    8:17  0    16M  0 part
├─sdb2    8:18  0 109,9G  0 part
├─sdb3    8:19  0     1G  0 part /boot
├─sdb4    8:20  0  101G  0 part /
└─sdb20 259:0    0  100G  0 part
sdg      8:96  1  57,3G  0 disk
└─sdg1    8:97  1  57,3G  0 part
sr0      11:0    1  1024M  0 rom


Nehmen wir an, wir würden den USB Stick {{ic|sdg}} formatieren wollen.
elif  [ -d $TARGET/daily.$DAYS ] && [ -d $TARGET/weekly.0 ] ; then


Als erstes wird das mit {{ic|gdisk}} ausgewählt.
    STAMP_0=`stat -c %Y $TARGET/daily.$DAYS`
    STAMP_1=`stat -c %Y $TARGET/weekly.0`


''HINWEIS:'' '''NICHT''' die Partitionsnummer auswählen, sondern das Gerät an sich! Also '''nicht''' {{ic|/dev/sdg1}} verwenden, sondern {{ic|/dev/sdg}}!
    #echo "$(( ($STAMP_0 - $STAMP_1)/(60*60*24) )) days difference between $TARGET/daily.$DAYS and $TARGET/weekly.0"
sudo gdisk /dev/sdg1


Danach kann man jede Partition durch Eingabe von {{ic|d}} löschen.
    if [ $(( ($STAMP_0 - $STAMP_1)/(60*60*24) )) -ge 7 ] ; then


Partition table scan:
          echo ""
  MBR: protective
          echo "Rotate Weekly Snapshots:"
  BSD: not present
  APM: not present
  GPT: present
Found valid GPT with protective MBR; using GPT.
Command (? for help): d
Using 1
Command (? for help):


Sollte man mehr als eine Partition auf dem Speichermedium haben, so müssen die Partitionsnummer danach noch eintippen.
# Step 1: Delete the oldest weekly snapshot, if it exists
        if [ -d $TARGET/weekly.$WEEKS ] ; then
            echo "rm -rf $TARGET/weekly.$WEEKS"
            rm -rf $TARGET/weekly.$WEEKS
        fi


Wenn alle Partitionen gelöscht wurden, kann man neue Partitionen durch die Eingabe von {{ic|n}} kreieren.
# Step 2: shift the middle snapshots by one.
Danach kann die Größe bestimmt werden. Wenn man beispielsweise eine 5GB große Partition erstellen will, kann man als ersten Sektor {{ic|-5G}} einsetzen.
        OLD=$WEEKS
        while [ $OLD -ge 1 ] ; do
                OLD=$[ $OLD - 1 ]
                if [ -d $TARGET/weekly.$OLD ] ; then
                        NEW=$[ $OLD + 1 ]
                        echo "mv $TARGET/weekly.$OLD $TARGET/weekly.$NEW"
                        mv $TARGET/weekly.$OLD $TARGET/weekly.$NEW
                fi
        done


Das {{ic|+}} bedeutet, dass er 5 GB ''übrig'' lässt! Da wir stattdessen 5GB ''für'' die Partition geben wollen, wird ein {{ic|-}} benötigt.
# Step 3: move oldest daily to weekly.0
        echo "mv $TARGET/daily.$DAYS $TARGET/weekly.0"
        mv $TARGET/daily.$DAYS $TARGET/weekly.0
    fi
fi


Danach kann man noch den Typ des Speichermediums eingeben. Hierfür wird als standard das Linuxdateisystem ausgewählt.
# -----------------Rotate Daily Snapshots---------------------------------------------


Das ist nur relevant, wenn man beispielsweise eine Boot-Partition anstatt eine "Speicher"-Partition erstellen möchte.
          echo ""
          echo "Rotate Daily Snapshots:"


Command (? for help): n
          if [ -d $TARGET/daily.$DAYS ] ; then
Partition number (1-128, default 1):
          echo "rm -rf $TARGET/daily.$DAYS"
First sector (34-120176606, default = 2048) or {+-}size{KMGTP}: -5G
                rm -rf $TARGET/daily.$DAYS
Information: Moved requested sector from 109690846 to 109688832 in
          fi
order to align on 2048-sector boundaries.
Use 'l' on the experts' menu to adjust alignment
Last sector (109688832-120176606, default = 120176606) or {+-}size{KMGTP}:
Current type is 8300 (Linux filesystem)
Hex code or GUID (L to show codes, Enter = 8300):
Changed type of partition to 'Linux filesystem'
Command (? for help):


'''Hinweis:'''
          OLD=$DAYS
          while [ $OLD -ge 2 ] ; do
                OLD=$[$OLD-1]
                if [ -d $TARGET/daily.$OLD ] ; then
                        NEW=$[ $OLD + 1 ]
                        echo "mv $TARGET/daily.$OLD $TARGET/daily.$NEW"
                        mv $TARGET/daily.$OLD $TARGET/daily.$NEW
                fi
          done


Mit {{ic|p}} kann man den aktuellen Stand des USB-Sticks betrachten, sodass man sich versichern kann, dass alles geklappt hat.
          echo ""
          echo "Copy Hardlinks:"
          if ! [ -d $TARGET/daily.0 ] ; then
                $MKDIR -p $TARGET/daily.0
          else
                echo "cp -al $TARGET/daily.0 $TARGET/daily.1"
                cp -al $TARGET/daily.0 $TARGET/daily.1 ;
                touch $TARGET/daily.1 --reference=$TARGET/daily.1/.timestamp
          fi


Command (? for help): p
          echo ""
Disk /dev/sdg: 120176640 sectors, 57.3 GiB
          echo "Starting Backup:"
Model: Ultra
          rsync -va --delete --delete-excluded --exclude-from="$EXCLUDES" --log-file=$TARGET/.rsync.log $SOURCE $TARGET/daily.0
Sector size (logical/physical): 512/512 bytes
Disk identifier (GUID): C823B7F7-D146-477B-B93D-E93975F17030
Partition table holds up to 128 entries
Main partition table begins at sector 2 and ends at sector 33
First usable sector is 34, last usable sector is 120176606
Partitions will be aligned on 2048-sector boundaries
Total free space is 109688798 sectors (52.3 GiB)
Number  Start (sector)    End (sector)  Size      Code  Name
  1      109688832      120176606  5.0 GiB    8300  Linux filesystem
Command (? for help):


Zu guter Letzt muss das alles nur noch auf den Stick, durch das Betätigen von {{ic|w}}, geschrieben werden.
          if ! [ $? = 24 -o $? = 0 ] ; then
                echo "rsync ended with ERRORS!"
                logger "rsync ended with ERRORS!"
                touch $TARGET/daily.0/.rsync_error
                touch $TARGET/daily.0/.timestamp
                exit
            else
                touch $TARGET/daily.0/.timestamp
                touch $TARGET/daily.0
                echo "Finished backup: $SOURCE to $TARGET with SUCCSESS"
                logger "Finished backup: $SOURCE to $TARGET with SUCCSESS"
          fi


{{ic|gdisk}} fragt dafür nochmal nach, ob man sich auch wirklich sicher ist, da es eventuell sein kann, dass man was vergessen hat.
if $MOUNT_RO ; then
        #echo "mount -o remount,ro $MOUNT_DEVICE $TARGET"
        mount -o remount,ro $MOUNT_DEVICE $TARGET
        if (( $? )); then
                echo "Error: Could not remount $TARGET readonly"
                exit
        fi
fi
</nowiki>


Wenn alles passt, die Operation mit {{ic|Y}} bestätigen.
<nowiki>


Command (? for help): w
## Datei: /[path]/snapshot_exclude.txt
Final checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING PARTITIONS!!
Do you want to proceed? (Y/N): Y
OK; writing new GUID partition table (GPT) to /dev/sdg.
The operation has completed successfully.


==== Formatieren ====


Jetzt ist die Partition da, jedoch noch kein Dateisystem.
Videos
tuxnix/.cache
</nowiki>


Dafür muss man jedichlich einfach {{ic|mkfs.<Dateisystem>}} verwenden.
=== Die  Service-Unit erstellen ===
Folgende Datei erstellen und abspeichern.
<nowiki>#file /etc/systemd/system/snapshot.service


Das {{ic|/dev/sdg1}} zeigt diesmal auf die '''Partition''', nicht auf das Speichermedium!
[Unit]
Description=snapshot.service


[diesen User@I use Arch btw] sudo mkfs.ext4 /dev/sdg1
[Service]
[sudo] Passwort für diesen User:
ExecStart=/usr/local/bin/snapshot.sh
mke2fs 1.45.5 (07-Jan-2020)
Ein Dateisystem mit 1310720 (4k) Blöcken und 328320 Inodes wird erzeugt.
UUID des Dateisystems: 2f2dbd1b-b054-49e0-aa10-852fd90764bf
Superblock-Sicherungskopien gespeichert in den Blöcken:
    32768, 98304, 163840, 229376, 294912, 819200, 884736
beim Anfordern von Speicher für die Gruppentabellen: erledigt
Inode-Tabellen werden geschrieben: erledigt
Das Journal (16384 Blöcke) wird angelegt: erledigt
Die Superblöcke und die Informationen über die Dateisystemnutzung werden
geschrieben: erledigt
[diesen User@I use Arch btw]


Und fertig ist man :)
</nowiki>


==== Benennen ====
=== Die Timer-Unit erstellen ===
Folgende Datei erstellen und abspeichern.
<nowiki>#file /etc/systemd/system/snapshot.timer


$ sudo e2label /dev/sdX1 SICHERUNG #Der Datenträger erhält das Label SICHERUNG
[Unit]
Description=snapshot.timer


==== Festplatte Einhängen ====
[Timer]
OnCalendar=daily
Persistent=true


$ sudo mkdir /SICHERUNG #Das Verzeichnis anlegen.
[Install]
WantedBy=basic.target


$ sudoedit /etc/fstab
</nowiki>
und hier folgendes einfügen:
/dev/sdX1 /SICHERUNG ext4 defaults 0 0
Am Ende der Datei muß eine Leerzeile eingefügt werden.
$ sudo mount /dev/sdX1 #Die Festplatte SICHERUNG wird auf /SICHERUNG ins Dateisystem eingebunden.


=== Das Backup Skript ===
=== Den Timer aktivieren ===
systemctl enable snapshot.timer


Falls auf dem System noch nicht vorhanden, wird rsync installiert.
Nach einem Neustart sorgt nun systemd für das regelmäßige Erstellen der gewünschten Backups.
$ sudo pacman -S rsync


Das folgende Skript wird kopiert und als {{ic|snapshot.sh}} z.B. in {{ic|~/.scripts/}} abgespeichert. Mit einem {{ic|chmod a+rx ~/.scripts/snapshot.sh}} wird es ausführbar gemacht.
Die ''CUSTOMIZING SECTION'' im Skript sollte auf die eigenen Gegebenheiten angepasst werden.


Die Datei {{ic|snapshot_exclude.txt}} wird ebenfalls kopiert und nach {{ic|~/.scripts/}} abgespeichert.
Alle in der snapshot_exclude.txt gelisteten Dateien und Verzeichnisse werden von einer Sicherung ausgeschlossen.


Danach kann mit folgendem Befehl die Funktion überprüft werden. Das Argument {{ic|-d}} erstellt ein tägliches Backup. Das Backup wird mit Rootrechten ausgeführt.
===Anhang===
$ sudo ~/.scripts/snapshot.sh -d
Beim original script werden 3 verschiedene Optionen genutzt:
* Option {{ic|-d}} erstellt ein tägliches Backup.
* Option {{ic|-w}} erstellt ein wöchentliches Backup.
* Option {{ic|-m}} erstellt ein monatliches Backup.


Bei einem erneuten Aufruf des Befehls erhöht sich der Zähler der jeweils vorangegangenen Sicherungen um 1. Eine dayly.0 Sicherung wird z.B.: in dayly.1 umbenannt, und eine neue dayly.0 Sicherung angelegt. Bei der Angabe von DAYS=6 in der ''CUSTOMIZING SECTION''; wird jeweils die 7. Sicherung gelöscht, bevor eine neue dayly.0 angelegt wird.
Dem entsprechend sind auch 3 systemd-timer und 3 systemd-services mit den entsprechenden ExecStart Befehlen anzulegen.
Die wöchentlichen und monatlichen Snapshots werden mit {{ic|sudo ~/.scripts/snapshot.sh -w}} bzw {{ic|sudo ~/.scripts/snapshot.sh -m}} ausgelöst.
Dabei wird keine neue Sicherung veranlasst, sondern lediglich, und auch nur dann wenn die Anzahl der täglichen Sicherungen komplettiert ist, die älteste der daily Sicherungen als weekly.0 kopiert und somit archiviert. Die weekly und monthly backups rotieren in der gleichen Weise wie die dailys.


Das Skript
Das original Skript
  <nowiki>#!/bin/bash
  <nowiki>#!/bin/bash
## Datei ~/.scripts/snapshot.sh
## Datei ~/.scripts/snapshot.sh
Zeile 466: Zeile 595:
<user>/Videos
<user>/Videos
</nowiki>
</nowiki>
=== Die  Service-Units erstellen ===
<nowiki>#file /etc/systemd/system/snapshot-d.service
[Unit]
Description=snapshot daily.service
[Service]
ExecStart=/home/<user>/.scripts/snapshot.sh -d
</nowiki>
Für die wöchentliche und monatliche Sicherung brauchen wir noch entsprechende snapshot-w.service und snapshot-m.service Dateien.
Das -d im der ExecStart= Option ist durch ein -w bzw. -m zu ersetzen. Bei Description= ist weekly bzw. monthly einzusetzen. Alle .service Dateien und auch die nachfolgenden .timer Dateien werden mit Rootrechten nach /etc/systemd/system/ gespeichert.
=== Die Timer-Units erstellen ===
<nowiki>#file /etc/systemd/system/snapshot-d.timer
[Unit]
Description=snapshot daily.timer
[Timer]
OnCalendar=daily
RandomizedDelaySec=60
Persistent=true
[Install]
WantedBy=basic.target
</nowiki>
Auch hier bedarf es einer weiteren Datei für den wöchentlich und auch einer weiteren Datei für den monatlichen Timer.
Die Dateien werden entsprechend benannt, dem OnCalendar= wird der Wert weekly bwz. monthly zugewiesen.
=== Die Timer aktivieren ===
systemctl enable --now snapshot-d.timer
systemctl enable --now snapshot-w.timer
systemctl enable --now snapshot-m.timer


== Siehe auch ==
== Siehe auch ==

Aktuelle Version vom 12. Dezember 2020, 00:34 Uhr

Dies ist Beispiel und Anleitung für ein automatisches, rotierendes und inkrementelles Backup. Das hier verwendete Skript (Original von Mike Rubbel im Anhang) baut auf dem rsync Befehl auf und sichert die Daten täglich, wöchentlich und monatlich. Hierzu wird ein Systemd-Timer genutzt. Das original Skript entstand 2004 und fand so viel Anklang, dass es in Perl übersetzt wurde und als rsnapshot Einzug in den Befehlspool von Linux hielt. Wer den Befehl diesem Skript vorzieht, kann auch diesen benutzen. Das Endergebnis dürfte jedoch gleich sein da beide rsync zum Speichern der Dateien einsetzen.

Hinweis: Da die Sicherung auf einer lokalen Festplatte stattfindet, kann sie weder bei Feuer noch bei einem Einbruch vor Datenverlust schützen.

Durch das automatische Sichern stellen Festplattendefekte und versehentliches Löschen keine Gefahr mehr da. Durch das rotierende Verfahren hat man die Möglichkeit, auf mehrere gesicherte Dateiversionen zuzugreifen. Trotzdem bleibt die Datenmenge gering. Rsync speichert die Daten jeweils nur einmal physisch ab und erstellt die einzelnen Schichten mittels Hardlinks. Da immer nur die jeweils veränderten Daten neu gesichert werden, ist die Geschwindigkeit des backups hervorragend.

Anleitung

Die Sicherungs-Festplatte

Der Sicherungs-Datenträger sollte fest in den Rechner verbaut werden. Der Datenträger muss ausreichend groß sein. Die folgenden Schritte sind als Beispiel zu verstehen:

Partitionieren

Der Datenträger wird wie in fdisk bzw. gdisk beschrieben mit 1. Partition versehen.

Formatieren

Als Format eignet sich ext4. Fat Systeme unterstützen keine Hardlinks.

mkfs.ext4 /dev/sdx1

Datenträger Benennen

Der Datenträger erhält das Label SICHERUNG

e2label /dev/sdx1 SICHERUNG

Festplatte Einhängen

Ein Verzeichnis SICHERUNG auf root (/) anlegen

mkdir /SICHERUNG

/etc/fstab

öffnen mit

nano /etc/fstab

und hier folgendes einfügen:

/dev/sdx1	/SICHERUNG	ext4	defaults	0	2

mounten

Das System Neustarten oder die Festplatte SICHERUNG auf /SICHERUNG ins Dateisystem einbinden.

mount /dev/sdx1 /SICHERUNG

Das Backup Skript

Falls auf dem System noch nicht vorhanden, wird jetzt rsync installiert.

pacman -S rsync

Das folgende Skript wird kopiert und als snapshot.sh in /usr/local/bin/ abgespeichert. Mit einem chmod a+rx /usr/local/bin/snapshot.sh wird es ausführbar gemacht.

Die CUSTOMIZING SECTION im Skript sollte auf die eigenen Gegebenheiten angepasst werden.

Die Datei snapshot_exclude.txt wird ebenfalls kopiert und nach /usr/local/bin/ gespeichert. Alle in der snapshot_exclude.txt gelisteten Dateien und Verzeichnisse werden von einer Sicherung ausgeschlossen.

Danach kann mit folgendem Befehl die Funktion überprüft werden. Das Backup wird mit Rootrechten ausgeführt.

snapshot.sh

Bein ersten Durchlauf werden alle Daten nach daily.0 kopiert. Bei einem erneuten Aufruf des Befehls wird daily.0 nach daily.1 kopiert. Danach wird die daily.0 mit dem aktuellen Stand aktualisiert. Bei der Angabe von DAYS=6 in der CUSTOMIZING SECTION; wird die spätere 7. Sicherung entweder als erste wöchentliche Sicherung umbenannt oder gelöscht, bevor die Sicherungen daily.5 bis daily.1 jeweils einen Zähler aufrücken.

Das Skript

#!/bin/bash
##
##      Script: snapshot.sh
## 
##      Creates daily, weekly and montly hardlink backupslices with rsync.
##
##      Version: 0.4
##
##      Original from:  Mike Rubel (http://www.mikerubel.org/computers/rsync_snapshots/)
## 
##      License:   LGPL
##
##      Disclaimer: Use this software on your own risk, it works for me but there are no guaranties at all.
## 
##      Changes from tuxnix:        *Only one systemd timer needed
##                                  *rsync.log
##                                  *Source directory choosable
##                                  
##                                              
## 
## ======================= CUSTOMIZING SECTION ========================

SOURCE='/NAS/  /home/tuxnix/'                        # Source needs a / at the end. More then only one SOURCE-Directories are possible (set ' ' marks).
EXCLUDES=/usr/local/bin/snapshot_exclude.txt         # full path of exludefile is needed

MOUNT_RO=true                                        # For remount with write protection set to true
MOUNT_DEVICE=/dev/disk/by-label/SICHERUNG            # Taget device
MOUNT_POINT=/SICHERUNG                               # Mount point of target device
TARGET=/SICHERUNG                                    # Target directory - full directory path of mounted device is needed

CHECK_HDMINFREE=true;         # Check free space
HDMINFREE=98;                 # Make a backup up to this percentage

DAYS=6;                       # Number of daily backups -1
WEEKS=3;                      # Number of weekly backups -1
MONTHS=11;                    # Number of monthly backups -1


# ---------------------- Check -----------------------------------------------------------------------------------------

# Make sure we're running as root
if (( `id -u` != 0 )); then { echo "Sorry, must be root.  Exiting..."; exit; } fi

# Check exludefile exists
if ! [ -f $EXCLUDES ] ; then { echo "Error: Exclude File $EXCLUDES missing"; exit; } fi


# Remount Device rw
if $MOUNT_RO ; then
        mount -o remount,rw $MOUNT_DEVICE $MOUNT_POINT
        if (( $? )) ; then
            echo "Error: could not remount $MOUNT_DEVICE readwriteable"
            exit
        fi
fi

# Check free space on disk
GETPERCENTAGE='s/.* \([0-9]\{1,3\}\)%.*/\1/'
if $CHECK_HDMINFREE ; then
        KBISFREE=`df /$TARGET | tail -n1 | sed -e "$GETPERCENTAGE"`
        if [ $KBISFREE -ge $HDMINFREE ] ; then
                echo "Error: Not enough space left for rotating backups!"
                logger "Error: Not enough space left for rotating backups!"
                exit
        fi
fi

# Give Source some time to wake up if needed.
ls $SOURCE > /dev/null
if (( $? )) ; then
    echo "Wait 10 seconds till $SOURCE device is arrivable."
    sleep 10
    ls $SOURCE > /dev/null
    if (( $? )); then
    echo "Can't read $SOURCE"
    exit
    fi
fi

# ---------------Rotate Monthly Snapshots------------------------------------------------------------------------------

if [ -d $TARGET/weekly.$WEEKS ] && ! [ -d $TARGET/monthly.0 ] ; then

    echo "mv $TARGET/weekly.$WEEKS $TARGET/monthly.0"
    mv $TARGET/weekly.$WEEKS $TARGET/monthly.0

elif [ -d $TARGET/weekly.$WEEKS ] && [ -d $TARGET/monthly.0 ] ; then

    STAMP_0=`stat -c %Y $TARGET/weekly.$WEEKS`
    STAMP_1=`stat -c %Y $TARGET/monthly.0`

    if [ $(( ($STAMP_0 - $STAMP_1)/(60*60*24) )) -ge 30 ] ; then

           echo ""
           echo "Rotate Monthly Snapshots:"

# Step 1: Delete the oldest monthly snapshot, if it exists
           if [ -d $TARGET/monthly.$MONTHS ] ; then
                echo "rm -rf $TARGET/monthly.$MONTHS"
                rm -rf $TARGET/monthly.$MONTHS 
           fi

# Step 2: Shift the middle snapshots by one
           OLD=$MONTHS
           while [ $OLD -ge 1 ] ; do
                OLD=$[$OLD-1]
                if [ -d $TARGET/monthly.$OLD ] ; then
                        NEW=$[ $OLD + 1 ]
                        echo "mv $TARGET/monthly.$OLD $TARGET/monthly.$NEW"
                        mv $TARGET/monthly.$OLD $TARGET/monthly.$NEW
                fi
           done

# Step 3: move oldest weekly to monthly.0
            echo "mv $TARGET/weekly.$WEEKS $TARGET/monthly.0"
            mv $TARGET/weekly.$WEEKS $TARGET/monthly.0 
           
    fi
fi

# ---------------Rotate Weekly Snapshots------------------------------------------------------------------------------

if [ -d $TARGET/daily.$DAYS ] && ! [ -d $TARGET/weekly.0 ] ; then

    echo "mv $TARGET/daily.$DAYS $TARGET/weekly.0"
    mv $TARGET/daily.$DAYS $TARGET/weekly.0

elif  [ -d $TARGET/daily.$DAYS ] && [ -d $TARGET/weekly.0 ] ; then

    STAMP_0=`stat -c %Y $TARGET/daily.$DAYS`
    STAMP_1=`stat -c %Y $TARGET/weekly.0`

    #echo "$(( ($STAMP_0 - $STAMP_1)/(60*60*24) )) days difference between $TARGET/daily.$DAYS and $TARGET/weekly.0"

    if [ $(( ($STAMP_0 - $STAMP_1)/(60*60*24) )) -ge 7 ] ; then

           echo ""
           echo "Rotate Weekly Snapshots:"

# Step 1: Delete the oldest weekly snapshot, if it exists
        if [ -d $TARGET/weekly.$WEEKS ] ; then
            echo "rm -rf $TARGET/weekly.$WEEKS"
            rm -rf $TARGET/weekly.$WEEKS
        fi

# Step 2: shift the middle snapshots by one.
        OLD=$WEEKS
        while [ $OLD -ge 1 ] ; do
                OLD=$[ $OLD - 1 ]
                if [ -d $TARGET/weekly.$OLD ] ; then
                        NEW=$[ $OLD + 1 ]
                        echo "mv $TARGET/weekly.$OLD $TARGET/weekly.$NEW"
                        mv $TARGET/weekly.$OLD $TARGET/weekly.$NEW
                fi
        done

# Step 3: move oldest daily to weekly.0
        echo "mv $TARGET/daily.$DAYS $TARGET/weekly.0"
        mv $TARGET/daily.$DAYS $TARGET/weekly.0
    fi
fi

# -----------------Rotate Daily Snapshots---------------------------------------------

           echo ""
           echo "Rotate Daily Snapshots:"

           if [ -d $TARGET/daily.$DAYS ] ; then
           echo "rm -rf $TARGET/daily.$DAYS"
                rm -rf $TARGET/daily.$DAYS
           fi

           OLD=$DAYS
           while [ $OLD -ge 2 ] ; do
                OLD=$[$OLD-1]
                if [ -d $TARGET/daily.$OLD ] ; then
                        NEW=$[ $OLD + 1 ]
                        echo "mv $TARGET/daily.$OLD $TARGET/daily.$NEW"
                        mv $TARGET/daily.$OLD $TARGET/daily.$NEW
                fi
           done

           echo ""
           echo "Copy Hardlinks:"
           if ! [ -d $TARGET/daily.0 ] ; then
                $MKDIR -p $TARGET/daily.0
           else
                echo "cp -al $TARGET/daily.0 $TARGET/daily.1"
                cp -al $TARGET/daily.0 $TARGET/daily.1 ;
                touch $TARGET/daily.1 --reference=$TARGET/daily.1/.timestamp
          fi

           echo ""
           echo "Starting Backup:"
           rsync -va --delete --delete-excluded --exclude-from="$EXCLUDES" --log-file=$TARGET/.rsync.log $SOURCE $TARGET/daily.0

           if ! [ $? = 24 -o $? = 0 ] ; then
                echo "rsync ended with ERRORS!"
                logger "rsync ended with ERRORS!"
                touch $TARGET/daily.0/.rsync_error
                touch $TARGET/daily.0/.timestamp
                exit
             else
                touch $TARGET/daily.0/.timestamp
                touch $TARGET/daily.0
                echo "Finished backup: $SOURCE to $TARGET with SUCCSESS"
                logger "Finished backup: $SOURCE to $TARGET with SUCCSESS"
           fi

if $MOUNT_RO ; then
        #echo "mount -o remount,ro $MOUNT_DEVICE $TARGET"
        mount -o remount,ro $MOUNT_DEVICE $TARGET
        if (( $? )); then
                echo "Error: Could not remount $TARGET readonly"
                exit
        fi
fi


## Datei: /[path]/snapshot_exclude.txt


Videos
tuxnix/.cache

Die Service-Unit erstellen

Folgende Datei erstellen und abspeichern.

#file /etc/systemd/system/snapshot.service

[Unit]
Description=snapshot.service

[Service]
ExecStart=/usr/local/bin/snapshot.sh


Die Timer-Unit erstellen

Folgende Datei erstellen und abspeichern.

#file /etc/systemd/system/snapshot.timer

[Unit]
Description=snapshot.timer

[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=basic.target


Den Timer aktivieren

systemctl enable snapshot.timer

Nach einem Neustart sorgt nun systemd für das regelmäßige Erstellen der gewünschten Backups.


Anhang

Beim original script werden 3 verschiedene Optionen genutzt:

  • Option -d erstellt ein tägliches Backup.
  • Option -w erstellt ein wöchentliches Backup.
  • Option -m erstellt ein monatliches Backup.

Dem entsprechend sind auch 3 systemd-timer und 3 systemd-services mit den entsprechenden ExecStart Befehlen anzulegen.

Das original Skript

#!/bin/bash
## Datei ~/.scripts/snapshot.sh
##
##
##      Mike Rubel 2004.01.04 (http://www.mikerubel.org/computers/rsync_snapshots/)
##
## License:
##      LGPL  
##
## Disclaimer:
##      Use this software on your own risk, it works for me but there
##      are no guaranties at all
## ----------------------------------------------
##
## make_snapshotLC: 
##      Backup Script based on rsync
##      It creates Generation Backups for the levels daily, weekly and montly
##
## Version:
##      0.3
##
## Synopsis:
##       make_snapshotLC [OPTIONS]
##
## Description:
##      This script was adopted from Mike Rubels documentation from
##      http://www.mikerubel.org/computers/rsync_snapshots/
##      Based on Mikes handy rotating-filesystem-snapshot utility.
##      The basic idea is it makes rotating backup-snapshots of /home whenever called
##      A few elements came from
##      http://www.heinlein-support.de/web/support/wissen/rsync-backup/
##      An exclude list avoids to backup superflous files.
##
## Changes:
##      Instead of hourly, daily and weekly snapshots, daily, weekly and monthly 
##      snapshots are used.
##      Checking the available space on backup media
##      Free configurable number of snapshots for every single level
##      Everything packed into one script
##
## Options:
##      -d make the daily backup plus rotate
##      -w make the weekly backup
##      -m make the monthly backup
##      -h displays a short help text
## 
## Changelog:
##      --------
########################################################################

unset PATH      # suggestion from H. Milz: avoid accidental use of $PATH

# ------------- System Commands used by this script --------------------
ID=/usr/bin/id;
ECHO=/bin/echo;
MOUNT=/bin/mount;
RM=/bin/rm;
MV=/bin/mv;
CP=/bin/cp;
TOUCH=/bin/touch;
RSYNC=/usr/bin/rsync;
DF=/bin/df;
TAIL=/usr/bin/tail;
SED=/bin/sed;
SYNC=/bin/sync;
LOGGER=/usr/bin/logger;
CHMOD=/bin/chmod;
MKDIR=/bin/mkdir;

# ======================= CUSTOMIZING SECTION ==========================
MOUNT_DEVICE=/dev/sdX1;                  # Your Mount device - Ziel
MOUNT_RO=true;                          # For write protection set to true
SNAPSHOT_RW=/SICHERUNG/;                 # where to store the backups - Ziel-Ordner
EXCLUDES=/home/<user>.scripts/snapshot_exclude.txt;    # Create the backup_exclude file first!
CHECK_HDMINFREE=true;                   # Check free space
HDMINFREE=90;                           # Make a backup up to this percentage
DAYS=6;                                 # Number of daily backups -1
WEEKS=3;                                # Number of weekly backups -1
MONTHS=3;                               # Number of monthly backups -1
# ======================================================================

# Make sure we're running as root
if (( `$ID -u` != 0 )); then { $ECHO "Sorry, must be root.  Exiting..."; exit; } fi

# Check Argument
if [ $# != 1 ] ; then { $ECHO "Error: Wrong number of arguments.  \
#Vaild is one out of -d, -w, -m, -h" ; exit; } fi

# Check Customization
if ! [ -b $MOUNT_DEVICE ] ; then { $ECHO "Error: Mount device $EXCLUDES isn't valid" ; exit; } fi
if ! [ -d $SNAPSHOT_RW ] ; then  $MKDIR -p $SNAPSHOT_RW; fi
if ! [ -f $EXCLUDES ] ; then { $ECHO "Error: Exclude File $EXCLUDES missing" ; exit; } fi

# Check free space on disk
GETPERCENTAGE='s/.* \([0-9]\{1,3\}\)%.*/\1/';
if $CHECK_HDMINFREE ; then
        KBISFREE=`$DF /$SNAPSHOT_RW | $TAIL -n1 | $SED -e "$GETPERCENTAGE"`
        if [ $KBISFREE -ge $HDMINFREE ] ; then
                $ECHO "Error: Not enough space left for rotating backups!"
                $LOGGER "Error: Not enough space left for rotating backups!"
                exit
        fi
fi

# ------------- The Script itself --------------------------------------

if $MOUNT_RO ; then
        # Attempt to remount the RW mount point as RW; else abort
        $MOUNT -o remount,rw $MOUNT_DEVICE $SNAPSHOT_RW ;
        if (( $? )); then
                $ECHO "Error: could not remount $SNAPSHOT_RW readwrite";
                exit;
        fi;
fi;


case $1 in
# *********** Daily Backups ********************************************
        -d | -D) $ECHO "Starting Daily Backup..."
           # Rotating daily snapshots of /home  

           # Step 1: Delete the oldest snapshot, if it exists:
           # It is NOT moved to the weekly backups level since you can make hundreds of daily backups
           if [ -d $SNAPSHOT_RW/daily.$DAYS ] ; then
                $RM -rf $SNAPSHOT_RW/daily.$DAYS ;
           fi;

           # Step 2: Shift all other snapshots(s) by one, if they exist (e.g. 6->7...1->2)
           OLD=$DAYS;
           while [ $OLD -ge 2 ] ; do
                OLD=$[$OLD-1]
                if [ -d $SNAPSHOT_RW/daily.$OLD ] ; then
                        NEW=$[ $OLD + 1 ]
                        # Save date
                        $TOUCH $SNAPSHOT_RW/.timestamp -r $SNAPSHOT_RW/daily.$OLD
                        $MV $SNAPSHOT_RW/daily.$OLD $SNAPSHOT_RW/daily.$NEW
                        # Restore date
                        $TOUCH $SNAPSHOT_RW/daily.$NEW/.timestamp \
                                -r $SNAPSHOT_RW/.timestamp
                fi;
           done

           # Step 3: make a hard-link-only (except for dirs) copy of the latest snapshot,
           # If that exists 0->1
           if ! [ -d $SNAPSHOT_RW/daily.0 ] ; then
                $MKDIR -p $SNAPSHOT_RW/daily.0
                $TOUCH $SNAPSHOT_RW/daily.0/.timestamp
           else
                $CP -al $SNAPSHOT_RW/daily.0 $SNAPSHOT_RW/daily.1 ;
           fi;

           # Step 4: rsync from the system into the latest snapshot (notice that
           # rsync behaves like cp --remove-destination by default, so the destination
           # is unlinked first.  If it were not so, this would copy over the other
           # snapshot(s) too!
           $RSYNC                                                               \
                -va --delete --delete-excluded                          \
                --exclude-from="$EXCLUDES"                              \
                /home $SNAPSHOT_RW/daily.0 ;

           # Check return code
           # 0 = ok, 
           # 24 is also ok. It appears if files were changed or deleted while this script runs
           # Other return codes are Error -- see man (1) rsync
           if ! [ $? = 24 -o $? = 0 ] ; then
                $ECHO "Error: rsync finished on $MOUNT_DEVICE with errors!"
                $LOGGER "Error: rsync finished on $MOUNT_DEVICE with errors!"
           fi;

           # Step 5: update the mtime of daily.0 to reflect the snapshot time
           $TOUCH $SNAPSHOT_RW/daily.0 ;

           # Finished!
           $ECHO "Finished rsync backup on $MOUNT_DEVICE..."
           $LOGGER "Finished rsync backup on $MOUNT_DEVICE..."

           # For beeing on the secure site...
           $SYNC;;

           # And thats it for home.

# *********** Weekly Backup ********************************************
        -w | -W)$ECHO "Starting Weekly Backup..."
        
           # Step 1: Delete the oldest snapshot, if it exists
           if [ -d $SNAPSHOT_RW/weekly.$WEEKS ] ; then
                $RM -rf $SNAPSHOT_RW/weekly.$WEEKS ;
           fi;
           
           # Step 2: shift the middle snapshots(s) by one, if they exist 3->4 ..0->1
           OLD=$WEEKS;
           while [ $OLD -ge 1 ] ; do
                OLD=$[$OLD-1]
                if [ -d $SNAPSHOT_RW/weekly.$OLD ] ; then
                        NEW=$[ $OLD + 1 ]
                        $MV $SNAPSHOT_RW/weekly.$OLD $SNAPSHOT_RW/weekly.$NEW ;
                fi;
           done

           # Step 3: Make a hard-link-only (except for dirs) copy of
           # daily.(max), assuming that exists, into weekly.0
           if [ -d $SNAPSHOT_RW/daily.$DAYS ] ; then
                $CP -al $SNAPSHOT_RW/daily.$DAYS $SNAPSHOT_RW/weekly.0 ;
           fi;;

# *********** Monthly Backup *******************************************
        -m | -M)$ECHO "Starting Monthly Backup..."
        
           # Step 1: Delete the oldest snapshot, if it exists
           if [ -d $SNAPSHOT_RW/monthly.$MONTHS ] ; then
                $RM -rf $SNAPSHOT_RW/monthly.$MONTHS ;
           fi;
           
           # Step 2: Shift the middle snapshots(s) by one, if they exist 6->7 ..0->1
           OLD=$MONTHS;
           while [ $OLD -ge 1 ] ; do
                OLD=$[$OLD-1]
                if [ -d $SNAPSHOT_RW/monthly.$OLD ] ; then
                        NEW=$[ $OLD + 1 ]
                        $MV $SNAPSHOT_RW/monthly.$OLD $SNAPSHOT_RW/monthly.$NEW ;
                fi;
           done

           # Step 3: Make a hard-link-only (except for dirs) copy of
           # weekly.(max), assuming that exists, into monthly.0
           if [ -d $SNAPSHOT_RW/weekly.$WEEKS ] ; then
                $CP -al $SNAPSHOT_RW/weekly.$WEEKS $SNAPSHOT_RW/monthly.0 ;
           fi;;

        -h | -H)$ECHO "Usage:
              make_snapshot -d  Initiates daily backup
              make_snapshot -w  Initiates weekly backup
              make_snapshot -m  Initiates monthly backup
              make_snapshot -h  Displays this text."; exit;;
        
        *) $ECHO "Error: Wrong argument. Vaild is one out of -d, -w, -m, -h" ; exit;;

esac

$ECHO "Backup ended"
if $MOUNT_RO ; then
        # Now remount the RW snapshot mountpoint as readonly
        $MOUNT -o remount,ro $MOUNT_DEVICE $SNAPSHOT_RW ;
        if (( $? )); then 
                $ECHO "Error: Could not remount $SNAPSHOT_RW readonly";
                exit;
        fi;
 fi;

## Datei ~/.scripts/snapshot_exclude.txt
##
<user>/.cache
<user>/.kodi
<user>/.local/share
<user>/.mediathek3
<user>/.mozilla
<user>/.tor-browser-de
<user>/.tvbrowser
<user>/Videos

Siehe auch

Weblinks