Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for each dir create a tar file

Tags:

linux

bash

shell

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
like image 558
Amanada Smith Avatar asked Apr 10 '13 20:04

Amanada Smith


People also ask

How do I create a tar file in a different directory?

The easy way, if you don't particularly need to use -C to tell tar to change to some other directory, is to simply specify the full path to the archive on the command line. Then you can be in whatever directory you prefer to create the directory structure that you want inside the archive.

How do I create a tar file?

To create a tar file, use the cvf command line option, list the name of the resulting tar file first followed by a directory whose contents you want to tar-up. If you forget to list the tar file target (hw10. tar) in the tar command, tar will exit with an error message.

Which option is used to create a tar file?

1. Creating an uncompressed tar Archive using option -cvf : This command creates a tar file called file. tar which is the Archive of all . c files in current directory.


3 Answers

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 {}  \;
like image 158
hzrari Avatar answered Oct 02 '22 08:10

hzrari


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.

like image 20
David W. Avatar answered Oct 02 '22 09:10

David W.


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
like image 26
Aaron Kelly Avatar answered Oct 02 '22 10:10

Aaron Kelly