Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a list of .tar.gz files with the same inner folder structure and I'd like to batch gunzip | untar a single file from them in separated folders.


I know the command to untar a single file is

tar -xvf {tarball.tar} {path/to/file}  

And adding the -C to specify the output folder the command for a single archive looks like:

tar -xvf logs_2013-08-01.tar.gz -C 2013-08-01/ /var/logs/audit

But how can I do a loop to untar everything?

share|improve this question
up vote 3 down vote accepted

You can try this (tested on Linux/bash):

for pkg in logs_*.tar.gz; do

   [ -d "$where" ] || mkdir "$where"

   tar zxfv $pkg -C "$where" /var/logs/audit

Simply, you loop over all the tgz archives in the current dircetory, then you take "date" part from its name, create required directory and extract them finally.

share|improve this answer
Just the solution I was asking for. – sergei Aug 22 '13 at 8:02

Use atool(1). It is already packaged for many distributions.

Just run:

$ atool -x -e *.tar.gz

to uncompress and untar every file in its own directory.

share|improve this answer
I'd like to avoid uncompressing everything due to lack of disk space in the server. – sergei Aug 22 '13 at 6:45
Take a look at atool's manpage, you can extract a single file too. – dawud Aug 22 '13 at 6:47
This was much easier than the above script. But installing atool is one additional step, but that's useful for future purposes as well. – Murali Paluru Jul 9 '15 at 1:07

You can simply loop over the files like this

# Pass the name of the file to unpack on the command line $1
for file in *.gz
    dir=$(echo "$file" | cut -c 6-15)
    tar -xvf "$file" -C "$dir" "$1"
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.