Bash – How to Gzip Multiple Subdirectories into Separate Archives

bashgziptar

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

Example:

directory
 subdir1
 subdir2

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

Best Answer

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.

Related Topic