BASH

Aus ConfigWiki
Wechseln zu: Navigation, Suche


dump-Backupskript

Enthält ein paar interessante Hacks.

 <source lang="bash">
#!/bin/bash
# Funktionen
function backup_age() {
  LEVEL=$1
  if ! test -f /tmp/backups/home/$LEVEL; then
       return 1
  fi
  LAST_DUMP=$(file /tmp/backups/home/$LEVEL \
       | grep -o "... ... .. ..:..:.. ...." | head -1)
  LAST_DUMP_EPOCH=$(date +%s -d "$LAST_DUMP")
  NOW_EPOCH=$(date +%s)
  echo $((NOW_EPOCH - LAST_DUMP_EPOCH))
}
function cleanup() {
  LEVEL=$1
  rm -f /tmp/backups/home/*.tmp
  for file in /tmp/backups/home/*
  do
       base=$(basename $file)
       test "$base" = "*" && break
       test "$base" -le $LEVEL && continue
       rm $file
  done
}

# Programm
if ! test $(id -u) = 0; then
  echo "$0: Keine Root-Rechte!" >&2
  exit 1
fi
if ! backup_age 0 \
  || test $(backup_age 0) -gt 604800; then
  dump -u -0 -f /tmp/backups/home/0.tmp /home \
  && mv /tmp/backups/home/0{.tmp,}
  cleanup 0
elif ! backup_age 1 \
  || test $(backup_age 1) -gt 86400; then
  dump -u -1 -f /tmp/backups/home/1.tmp /home \
  && mv /tmp/backups/home/1{.tmp,}
  cleanup 1
else
  dump -u -2 -f /tmp/backups/home/2.tmp /home \
  && mv /tmp/backups/home/2{.tmp,}
  cleanup 2
fi
</source>

Datei einer bestimmten Größe mit zufälligem Inhalt erstellen

Brauchbar z.B. für Bandbreitentests.

 <source lang="bash">
dd if=/dev/urandom bs=1M count=4096 of=4gb_testdatei
</source>

In diesem Beispiel wird eine 4GB große Datei erstellt.

Zufälligen String mit einer definierten Länge erzeugen

  • Kann z.B. zum erzeugen eines neuen Passwortes genutzt werden.
  • Das Bsp.-script prüft:
    • ob ein Parameter für die Länge des zu erzeugenden Strings übergeben wird,
    • ob dieser ein Integer ist
    • und dieser kleiner als 1000000 ist (dient gegen Rechnerstress).
  • Die Standardlänge des Strings ist hier 10 Zeichen.
<source lang="bash"> 
#!/bin/bash

#
# function for random string
#
function randstrg () {
        local strgLength
        local strg
        if [ $1 ]; then
                strgLength=$1
        else
                strgLength=10
        fi
 
        strg=</dev/urandom tr -dc A-Za-z0-9 | head -c $strgLength
        return $strg
}

#
# ERROR-handling if parameter 1 set, not to big  and not a integer
#
if [ ${1} ]; then
    if [ ! $(echo "${1}" | grep -E "^[0-9]+$") ] || [ "${1}" -gt 1000000 ]; then
       echo 'wrong 1. parameter ( Must be an INTEGER <= 1000000! )'
       echo 'usage:'
       echo "${0} [ INTEGER ]"
       exit
    fi
fi

#
# GO
#
strg= randstrg ${1}
echo $strg
</source>