0

I have several directories that I want to backup to a zip file with a shell script. Directory tree looks like this:

testing
     |_ source
     |     |_ fiction_01
     |     |_ fiction_02
     |     |_ ...
     |     |_ images
     |
     |_ destination

I only want to zip directories starting with the same pattern, say, f*. Not interested in images. The resulting zip should be saved to destination. From here, I get how to filter all directories whose name start with f. This is my code:

#!/bin/bash

# source and destination directories passed as 1st and 2nd parameters respectively
 SRCDIR=$1
 DESTDIR=$2

# children directories are those matching f*
 CHLDIR=$(find "$SRCDIR" -type d -name "f*") 

# name with timestamp for the .zip 
 BKPNAME=backup-$(date +%-Y%-m%-d)-$(date +%-T).zip

# actual zipping
 zip -r $DESTDIR$BKPNAME $SRCDIR$CHLDIR

The script is named backup.sh and lives in destination. This is what I get after running it:

jm@lenovo410:~/Documents/testing/destination$ bash backup.sh ../source/ ./
  adding: ../source/../source/fiction_02/ (stored 0%)
  adding: ../source/../source/fiction_02/another.txt (stored 0%)
  adding: ../source/fiction_01/ (stored 0%)
  adding: ../source/fiction_01/list.txt (stored 0%)

The zip file is created in destination directory. Even though it seems both fiction_01 and fiction_02 (and their content) were added, when I check inside the zip there is only directory fiction_01.

Question: How can I zip all folders whose name match the condition f*?

canovasjm
  • 501
  • 1
  • 3
  • 11

1 Answers1

1

The pathnames returned by find already begin with $SRCDIR, you don't need to concatenate it when you run zip. You're trying to add /testing/source/testing/source/fiction_01 to the zip file.

zip -r $DESTDIR$BKPNAME $CHLDIR

When you're debugging a shell script, one the best tools is to put set -x at the beginning. Then you'll see a trace of all the commands that are executed, with variables expanded. Then you would have seen these incorrect pathnames.

Barmar
  • 741,623
  • 53
  • 500
  • 612