diff --git a/README.md b/README.md index f9eb568..5fbef0d 100644 --- a/README.md +++ b/README.md @@ -51,3 +51,14 @@ Make it executable before scheduling it with `cron`: ```bash chmod +x scripts/backup_mongodb.sh ``` +Store `DBNAME` (and optional credentials) in environment variables rather than +editing the script. You may create a file named `~/.mongodb_backup_env` with +content like: + +```bash +export DBNAME="fmriprep_stats" +# export MONGO_USER=myuser +# export MONGO_PASS=mypassword +``` + +The backup script will source this file if present. diff --git a/scripts/backup_mongodb.sh b/scripts/backup_mongodb.sh index 7fb692f..0532a77 100644 --- a/scripts/backup_mongodb.sh +++ b/scripts/backup_mongodb.sh @@ -2,11 +2,20 @@ # scripts/backup_mongodb.sh # Backup MongoDB database, ensuring mongod is running. +set -euo pipefail + +# Optionally source credentials from ~/.mongodb_backup_env +ENV_FILE="$HOME/.mongodb_backup_env" +if [ -f "$ENV_FILE" ]; then + # shellcheck disable=SC1090 + source "$ENV_FILE" +fi + +# DBNAME is required; credentials are optional +: "${DBNAME:?Set DBNAME, e.g., export DBNAME=your_db}" + DATE=$(date +%Y-%m-%d) -BACKUP_DIR="$HOME/Dropbox/backups" -DBNAME="DBNAME" -USERNAME="USERNAME" -PASSWORD="PASSWORD" +BACKUP_DIR="$HOME/Dropbox/fmriprep_stats" BACKUP_PATH="$BACKUP_DIR/db_backup_${DATE}" mkdir -p "$BACKUP_DIR" @@ -27,8 +36,17 @@ else started_mongod=true fi +# Build mongodump options +dump_opts=(--db "$DBNAME" --out "$BACKUP_PATH") +if [ -n "${MONGO_USER:-}" ]; then + dump_opts+=(--username "$MONGO_USER") +fi +if [ -n "${MONGO_PASS:-}" ]; then + dump_opts+=(--password "$MONGO_PASS") +fi + # Dump the database -mongodump --db "$DBNAME" --username "$USERNAME" --password "$PASSWORD" --out "$BACKUP_PATH" +mongodump "${dump_opts[@]}" # Stop mongod if we started it if [ "$started_mongod" = true ]; then