Skip to content

Instantly share code, notes, and snippets.

@pajtai
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pajtai/73de4a045e40fc510707 to your computer and use it in GitHub Desktop.
Save pajtai/73de4a045e40fc510707 to your computer and use it in GitHub Desktop.
Backup mongo data to a directory and clear directory of old files.
#!/usr/bin/env bash
set -e
#set -x # for debugging
# daily backups with logs crontab -e example:
# 0 1 * * * /home/user/path/to/this/file -u my-user -p 'my-pw' -d mydb -t 90 >>/home/user/logs/backup.log 2>&1
MONGO_PW=""
TTL=180
while test $# -gt 0; do
case "$1" in
-h|--help)
echo "Database backup."
echo " "
echo "Creates a mongo dump in ~/backups and packages it in a tar.gz"
echo " "
echo "options:"
echo "-h, --help show help"
echo "-u, --user mongo user"
echo "-p, --password mongo user password"
echo " to be prompted for a password, do not include this flag"
echo "-d, --database mongo database - defaults to theme if not provided"
echo "-t, --ttl time to live of files in days"
echo " files older than ttl days will be deleted"
exit 0
;;
-u|--user)
shift
MONGO_USER=$1
shift
;;
-p|--password)
shift
MONGO_PW=$1
shift
;;
-d|--database)
shift
MONGO_DB=$1
shift
;;
-t|--ttl)
shift
TTL=$1
shift
;;
*)
break
;;
esac
done
echo " "
THE_THEME="$MONGO_DB"
THE_DATE=$(date +'%Y-%m-%d-%T' | sed 's/:/_/g')
THE_DIR="$THE_THEME-$THE_DATE"
echo "the dir: $THE_DIR"
cd ~/backups
mkdir $THE_DIR
cd $THE_DIR
echo "starting mongo backup u:$MONGO_USER d:$MONGO_DB"
mongodump -u $MONGO_USER -p $MONGO_PW --db $MONGO_DB --out ./
echo " "
cd ~/backups
TAR_FILE="$THE_THEME-$THE_DATE.tar.gz"
tar --remove-files -zcvf $TAR_FILE $THE_DIR
echo "Done backuping up $THE_THEME"
echo " "
echo "Checking for old files to delete"
find ~/backups -type f -mtime +$TTL -delete
echo "--------------------------------------------"
echo " "
echo " "
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment