Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create multiple tar.gz archives from multiple directories

Tags:

bash

shell

sh

gzip

tar

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.

like image 670
jzg.dev Avatar asked Jan 23 '26 04:01

jzg.dev


2 Answers

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.

like image 109
Benjamin W. Avatar answered Jan 25 '26 04:01

Benjamin W.


With GNU find:

cd /Users/Me/Projects
find . -maxdepth 1 -mindepth 1 -type d -exec tar -cvzf {}.tgz {} \;
like image 43
Cyrus Avatar answered Jan 25 '26 04:01

Cyrus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!