简体   繁体   中英

Send email with file attachments as bash array

Below is a snippet is taken from a WordPress backup bash script run via cron.

do
    file="$MDB/$db.$now.sql.gz"
    mysqldump -u $USER -h $HOST -p$PASS $db | gzip -9 > $file
    echo "Backup $file.....DONE"
    echo "Database Backup of $file" | mutt -a "$file" -s "Database Backup File Attached" -- theemail@gmail.com
    echo "Emailing $file.... DONE"
done

Notice in the emailing the backups part. The files are emailed one by one, therefore with 10 database backups, there'll be 10 emails sent.

I want to accumulate the files into an array in the for loop, then via mutt , send one single email including all the files as an attachment.

How can it be done in Bash?

Simply add the value of file to an array inside the loop.

declare -a files
...
do
    file="$MDB/$db.$now.sql.gz"
    mysqldump -u "$USER" -h "$HOST" -p"$PASS" "$db" | gzip -9 > "$file"
    files+=("$file")
done

echo "Backup ${files[*]}.....DONE"
echo "Database Backup" | mutt -s "Database Backup Files Attached" -a "${files[@]}" -- theemail@gmail.com
echo "Emailing ${files[*]}.... DONE"

A few notes:

  1. Use ${files[*]} when including the list in a string; use ${files[@]} when each element should be a separate argument.
  2. With multiple arguments, -a must be the last option before -- .
  3. You probably don't want to include every backup name in the subject.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM