Michael Garrison
Michael Garrison

Reputation: 941

Bash Script - Compress multiple directories in one archive

I made a script a while back that would use zip to compress several different user specified directories. The way the script did this is it would read the directories from config.txt and compress each one individually. It just so happens that, for my uses, all of these directories are in the same parent. For instance, I'll have the following directories in my /Users/username/ directory:

Desktop
Documents
Pictures

Is there a way to combine these 3 in the same archive?

For a reference, here is my current script:

BKUPDATE="/Users/michaelgarrison/Backup/BKUP_"$(date +%Y)-$(date +%m)-$(date +%d)

# Create the Backup directory if it does not exist
mkdir -p $BKUPDATE

# File where directories are specified
CONFIG="config.txt"

while read SOURCE
do
    DESTINATION="/Users/michaelgarrison/"
    OUTPUT=$BKUPDATE"/Backup_"$SOURCE"_"$(date +%Y)-$(date +%m)-$(date +%d)".zip"
    (cd /Users/michaelgarrison/; zip -r $OUTPUT $SOURCE)
done < $CONFIG

Upvotes: 3

Views: 7733

Answers (3)

D-E-N
D-E-N

Reputation: 1272

please read the comments and answers, they answered your question in a good way!!

  • put constant things out of the loop

OUTPUT="/Users/michaelgarrison/"$BKUPDATE"/Backup_"$(date +"%Y-%m-%d")".zip" DESTINATION="/Users/michaelgarrison/" <--------- do you need this? I think you don't

while read SOURCE
do
    zip -r $OUTPUT $SOURCE
done < $CONFIG

If you want to do this more than once, you may can use rsync

Upvotes: 1

Hayden
Hayden

Reputation: 2112

zip -r backup Desktop/* Documents/* Pictures/*

That would compress all the files under Desktop, Documents and Pictures under a file named backup.zip

The trick of sorts would be reading the list from the config.txt file, presumably a vertical list or array and making it one long string.

Upvotes: 11

Michael Garrison
Michael Garrison

Reputation: 941

I think I just answered my own question, but instead of deleting I'll leave it here for future reference. What I did was change the output to the same zip file for each pass.

What I did was change:

while read SOURCE
do
    DESTINATION="/Users/michaelgarrison/"
    OUTPUT=$BKUPDATE"/Backup_"$SOURCE"_"$(date +%Y)-$(date +%m)-$(date +%d)".zip"
    (cd /Users/michaelgarrison/; zip -r $OUTPUT $SOURCE)
done < $CONFIG

to:

OUTPUT=$BKUPDATE"/Backup_"$(date +%Y)-$(date +%m)-$(date +%d)".zip"
while read SOURCE
do
    DESTINATION="/Users/michaelgarrison/"
    (cd /Users/michaelgarrison/; zip -r $OUTPUT $SOURCE)
done < $CONFIG

Upvotes: 0

Related Questions