jzg.dev jzg.dev - 7 months ago 10
Bash Question

Create multiple tar.gz archives from multiple directories

I have a directory full of projects inside, let's say

/Users/Me/Projects
.

Inside of this folder are multiple sub-directories, and even more sub-directories within some of those.

I would like to be able to create a
tar.gz
archive of each archive within
/Users/Me/Projects
, the archives of which would have the same name as the directory.

For example, in the
Projects
folder I'd have,
Project1
,
Project2
, and
Project3
.

What I would like, is to run a script to loop over the directories in
Projects
and not the sub-directories below that to create
Project1.tar.gz
,
Project2.tar.gz
, and
Project3.tar.gz
.

Answer

Without find:

for dir in */; do tar -czvf "${dir%/}".tar.gz "$dir"; done

where */ makes sure that the glob only matches directories, and "${dir%/}" removes the trailing slash from directory names.

If there are hidden directories, they're not matched by /*; do get those as well, we can use shopt -s dotglob.

Comments