0

Answering my own question yesterday, I wrote a bash script which archives all directories within a defined directory into their own separate archive files. I have also defined a variable for a file which would include a list of directories I would like to skip. I wanted it to work something like the --exclude-from parameter for tar, but obviously that would not work. What is the best way I can accomplish this? I am thinking that grep would be the path I should take.

#!/bin/bash

#START
TIME=`date +%Y-%m-%d_%Hh%Mm`     # Append date and time to backup file
SRCDIR=/srv                      # Location of directories to backup
DESDIR=/srv/backup               # Destination of backup files
EXCLUDE=exclude.txt  # File which defines what to exclude from archiving

for dir in $SRCDIR/*/
do
  base=$(basename "$dir")
  tar -cpzf $DESDIR/$base-$TIME.tar.gz $dir
done
#END
1

You can use grep to check if the directory is listed in your exclude file, as shown in this answer on SO:

#!/bin/bash

#START
TIME=`date +%Y-%m-%d_%Hh%Mm`     # Append date and time to backup file
SRCDIR=/srv                      # Location of directories to backup
DESDIR=/srv/backup               # Destination of backup files
EXCLUDE=exclude.txt  # File which defines what to exclude from archiving

for dir in $SRCDIR/*/
do
  base=$(basename "$dir")
  if grep -Fxq "$base" $EXCLUDE
  then
    echo "$base excluded"
  else
    tar -cpzf $DESDIR/$base-$TIME.tar.gz $dir
  fi
done
#END

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.