How to create .tar files for all folders under a directory

I have hundreds of project directories under one folder. Now I want to create .tar files for these projects. Is is fairly easy to tar multiple directories to one .tar file:

tar cvf /myStorage/allProjects.tar project1 project2 project3 project4

But I needed one .tar file per project. To keep .tar files seperate. So I needed to have:

/myStorage/project1.tar
/myStorage/project2.tar
/myStorage/project3.tar
/myStorage/project4.tar

To accomplish this, I needed to write a bash script:

#!/bin/bash
#
# Create .tar files for the source folder in destination
# v0.2 21Jan2013
# kuban.altan@gmail.com
#
# tarchive mySourceDirectory myDestination Directory

sourceDir=$1
destDir=$2

sourceFiles=$sourceDir/*
cd $sourceDir
pwd

SAVEIFS=$IFS
IFS=$(echo -en "\n\b")

for f in $sourceFiles
do
currentFile=$(basename $f)
legalCurrentFile=${currentFile//[^a-zA-Z0-9]/_}
echo "tar cvf "$destDir/$legalCurrentFile.tar" "$currentFile""
tar cvf "$destDir/$legalCurrentFile.tar" "$currentFile"
done

# restore $IFS
IFS=$SAVEIFS

All you need to write is:

tarchive mySourceProjectDirectory myDestinationDirectory

As the result, I will have a seperate .tar file for each project directory in myDestionationDirectory.

Yorum bırakın