Amanada Smith
Amanada Smith

Reputation: 1981

for each dir create a tar file

I have a bunch of directories that need to be restored, but they have to first be packaged into a .tar. Is there a script that would allow me to package all 100+ directories into their own tar so dir becomes dir.tar.

So far attempt:

for i in *; do tar czf $i.tar $i; done

Upvotes: 38

Views: 29707

Answers (5)

Mark Setchell
Mark Setchell

Reputation: 207375

Get them all done simply and in parallel with GNU Parallel:

parallel tar -cf {}.tar {} ::: *

If you want to check what it is going to do without actually doing anything, add --dry-run like this:

parallel --dry-run tar -cf {}.tar {} ::: *

Sample Output

tar -cf ab.tar ab
tar -cf cd.tar cd

Upvotes: 4

hzrari
hzrari

Reputation: 1933

The script that you wrote will not work if you have some spaces in a directory name, because the name will be split, and also it will tar files if they exist on this level.

You can use this command to list directories not recursively:

find . -maxdepth 1 -mindepth 1 -type d

and this one to perform a tar on each one:

find . -maxdepth 1 -mindepth 1 -type d -exec tar cvf {}.tar {}  \;

Upvotes: 88

Aaron Kelly
Aaron Kelly

Reputation: 49

If there are spaces in the directory names, then just put the variables inside double quotes:

for i in *
 do
     tar czf "$i.tar" "$i"
 done

Upvotes: 4

Jalal Hajigholamali
Jalal Hajigholamali

Reputation: 379

if number of directories are very large and their names are too long

after execution of statement number one

  for i in *
    do
     echo tar czf $i.tar $i
    done

you will get error "string too long"

Upvotes: 1

David W.
David W.

Reputation: 107040

Do you have any directory names with spaces in them at that level? If not, your script will work just fine.

What I usually do is write a script with the command I want to execute echoed out:

$ for i in *
do
    echo tar czf $i.tar $i
done

Then you can look at the output and see if it's doing what you want. After you've determined that the program will work, edit the command line and remove the echo command.

Upvotes: 7

Related Questions