Skip to content

didbackup.sh

Carl Joakim Damsleth edited this page Feb 1, 2024 · 2 revisions
#!/bin/zsh

# This is a PoC backup script for did database backups
# It loops through all databases in the specified mongo replica set
# and dumps them to the current folder

# exit codes
# 0 - success
# 1 - no connection string specified
# 2 - mongosh command not on system
# 3 - mongodump not found on system

# check if connection string is specified
if [[ -z $1 ]] || [[ $# -lt 1 ]];then
    echo "ERROR: no connection string specified, exiting"
    exit 1
fi

# check if connection string is specified
if [[ -z $2 ]];then
    echo "No database specified, dump all in replica set"
fi

# check if mongo is installed
if ! command -v mongosh &> /dev/null
then
    echo "ERROR: mongosh not found on system"
    exit 2
fi

# check if mongodump is installed
if ! command -v mongodump &> /dev/null
then
    echo "ERROR: mongodump not found on system"
    exit 3
fi

CONNECTION_STRING=$1
echo "Getting database names with mongo"

# Fetch database names
DATABASES=`mongosh "$CONNECTION_STRING" --eval "db.getMongo().getDBNames()" | grep "\[" | sed 's:^.\(.*\).$:\1:'`

echo "Databases in replica set:"
echo $DATABASES | tr "," "\n"
if [[ -z $2 ]]
then 
    echo "backing up all databases: $db";
    mongodump --uri="$CONNECTION_STRING" --out ./$(date +"%Y-%m-%dT%H:%M")/
else
    echo "backing up database $2";
    mongodump --uri="$CONNECTION_STRING" --db=$2 --out ./$(date +"%Y-%m-%dT%H:%M")/
fi

echo "backup finished at $(date +"%Y-%m-%dT%H:%M:%S")"

exit 0;