Skip to content

Instantly share code, notes, and snippets.

@nhr
Created April 29, 2015 20:06
Show Gist options
  • Save nhr/5a66cd1a3d4f294c8a5d to your computer and use it in GitHub Desktop.
Save nhr/5a66cd1a3d4f294c8a5d to your computer and use it in GitHub Desktop.
Shell script for copying / restoring qcow2 image files. Be warned: this does not check to make sure that the files are not currently in use!
#!/bin/bash
RESTORE=false
RESTORE_DIR=''
while getopts ":r:" OPT; do
case $OPT in
r)
RESTORE_DIR="$OPTARG"
RESTORE=true
;;
\?)
echo "Invalid option: -$OPTARG"
exit 1
;;
:)
RESTORE=true
;;
esac
done
shift $((OPTIND-1))
: ${LABSNAP_SRC_DIR:?"Set LABSNAP_SRC_DIR to the directory where your lab qcow2 images live."}
: ${LABSNAP_TGT_DIR:?"Set LABSNAP_TGT_DIR to the directory where your snapshot images will live."}
SRC_DIR=${LABSNAP_SRC_DIR%/}
TGT_DIR=${LABSNAP_TGT_DIR%/}
create_snapshot () {
SNAPDIR=`date '+%Y-%m-%d-%H%M%S'`
if [[ -d "$TGT_DIR/$SNAPDIR" ]]; then
echo "You're trying to create two snapshots in the same second. Try again."
exit 1
fi
mkdir "$TGT_DIR/$SNAPDIR"
cp $SRC_DIR/*.qcow2 $TGT_DIR/$SNAPDIR
echo "New snapshot(s) created in $TGT_DIR/$SNAPDIR"
}
restore_snapshot () {
SNAPDIR=`ls $TGT_DIR | tail -1`
if [[ -z "$1" ]]; then
echo "Restoring latest snapshot ($SNAPDIR)";
else
if [[ ! -d "$TGT_DIR/$1" ]]; then
echo "Snapshot $1 does not exist."
exit 1
fi
SNAPDIR=$1
fi
cp $TGT_DIR/$SNAPDIR/*.qcow2 $SRC_DIR
echo "Snapshots restored from $SNAPDIR"
}
if [[ "$RESTORE" == true ]]; then
restore_snapshot $RESTORE_DIR
else
create_snapshot
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment