19

How would I be able to compress subdirectories into separate archives?

Example:

directory
 subdir1
 subdir2

Should create subdir1(.tar).gz and subdir2(.tar).gz

Juliano
  • 5,592
aardbol
  • 1,493

4 Answers4

32

This small script seems to be your best option, given your requirements:

cd directory
for dir in */
do
  base=$(basename "$dir")
  tar -czf "${base}.tar.gz" "$dir"
done

It properly handles directories with spaces in their names.

Juliano
  • 5,592
15

How about this: find * -maxdepth 0 -type d -exec tar czvf {}.tar.gz {} \;

Explanation: You run a find on all items in the current directory. Maxdepth 0 makes it not recurse any lower than the arguments given. (In this case *, or all items in your current directory) The 'd' argument to "-type" only matches directories. Then exec runs tar on whatever matches. ({} is replaced by the matching file)

5

This will create a file called blah.tar.gz for each file in a directory called blah.

$ cd directory
$ for dir in `ls`; do tar -cvzf ${dir}.tar.gz ${dir}; done

If you've got more than simply directories in directory (i.e. files as well, as ls will return everything in the directory), then use this:

$ cd directory
$ for dir in `find . -maxdepth 1 -type d  | grep -v "^\.$" `; do tar -cvzf ${dir}.tar.gz ${dir}; done

The grep -v excludes the current directory which will show up in the find command by default.

0

flowing @Philip Reynolds answer (needed 50 points reputation to comment, so adding....)

*for dir in `find . -maxdepth 1 -type d  | grep -v "^\.$" `; do echo "tar -cvzf ${dir}.tar.gz ${dir}"; done*

commands will be written to terminal but not launched, copy and past to text file remove unwanted commands. don't trust resulting commands blindly. avoid trashing some files and folders .