Linux gzip multiple subdirectories into separate archives?

Solution 1:

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.

Solution 2:

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)


Solution 3:

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.

Tags:

Bash

Tar

Gzip