Skip to content

Instantly share code, notes, and snippets.

@mdukat
Created June 14, 2019 08:23
Show Gist options
  • Save mdukat/fdd8a863612170a007ac3aaf771a9060 to your computer and use it in GitHub Desktop.
Save mdukat/fdd8a863612170a007ac3aaf771a9060 to your computer and use it in GitHub Desktop.
Simple, easily extensible, /var/log backup script
#!/bin/bash
# Variables (aka config)
# Script executed after making backup of /var/log (none for no script to execute)
passScript=""
# Remove syslog, auth.log, kern.log, after backup? ("true"/"false")
removeAfterVarlog="true"
# Remove backup tar from /tmp. Good when uploading with passScript ("true"/"false")
removeAfterTar="false"
err_exit () {
echo "Exiting..."
exit
}
# Check if we can read /var/log files
if [ -d "/var/log" ]; then
echo "/var/log Exists"
else
echo "[ERR] /var/log Does not exist!"
err_exit
fi
for i in "auth.log" "kern.log" "syslog"
do
if [ -r "/var/log/$i" ]; then
echo "/var/log/$i Is readable"
else
echo "[ERR] /var/log/$i Does not exist, or is not readable!"
err_exit
fi
done
# Check if we have every command we need
for i in "du" "md5sum" "tail" "tar" "xz"
do
if [ -x "$(command -v $i)" ]; then
echo "Found $i"
else
echo "[ERR] $i Not found, or not executable!"
err_exit
fi
done
# Check how much space will tar take
tarSpace=$(du -hc /var/log | tail -1)
echo "Backup will take around $tarSpace"
# Check if /tmp exists, check if theres no another file with same name, and write a tar archive
if [ ! -d "/tmp" ]; then
echo "[ERR] /tmp Does not exist! What the hell?!"
err_exit
fi
echo "Making tar archive of /var/log..."
tarFileName="$(date "+%d.%m.%y_%R")_varlog.tar"
echo "Name: /tmp/$tarFileName"
if [ -f /tmp/$tarFileName ]; then
echo "[ERR] /tmp/$tarFileName exists!"
err_exit
fi
tar cvf /tmp/$tarFileName /var/log/*
xz /tmp/$tarFileName
tarFileName="$tarFileName.xz"
# Check if /tmp/tar is made properly
if [ ! -f /tmp/$tarFileName ]; then
echo "[ERR] /tmp/$tarFileName does not exist! Something went wrong!"
err_exit
fi
# Make md5sum of backup tar
printf "md5: "
md5sum /tmp/$tarFileName
# Execute another script with tar filename passed
## This is used for remote backup, or whatever you want to do with backup file
if [ ! $passScript = "" ]; then
echo "Running $passScript"
$passScript "/tar/$tarFileName"
else
echo "No passScript specified"
fi
# Remove things from /var/log **CRITICAL**
if [ $removeAfterVarlog = "true" ]; then
echo "Removing old logs..."
rm /var/log/kern.log* /var/log/auth.log* /var/log/syslog*
fi
# Remove backup file
if [ $removeAfterTar = "true" ]; then
echo "Removing backup tar..."
rm /tmp/$tarFileName
fi
# Done
echo "Done, have a nice day"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment