For-loop not working

Hello all,

I would like to unzip some files with a for-loop.

Is there anyone who could tell me how I should do this - in a correct way?

for file in $(ls); do echo gzip -d < $file | tar xf -; done

The problem is the pipe - I believe. But how could I do it? I need it for the command line. To do it with a script is not the solution - in this case.

You need to send the output of gzip to stdout, using the -c option. If your files end with .tar.gz try:

for file in *.tar.gz ; do gzip -cd "$file" | tar xf -; done

Some tar implementations recognize a gzipped or compressed file and you can use

for file in *.tar.gz ; do tar xf "$file"; done
1 Like

Wouldn't tar need the z command, then?

Perhaps with some tars you need the -z option.

... At least with BSD tar:

     -y      (c mode only) Compress the resulting archive with bzip2(1).  In extract or list modes, this option is ignored.  Note that,
             unlike other tar implementations, this implementation recognizes bzip2 compression automatically when reading archives.

     -z      (c mode only) Compress the resulting archive with gzip(1).  In extract or list modes, this option is ignored.  Note that, unlike
             other tar implementations, this implementation recognizes gzip compression automatically when reading archives.

     -Z      (c mode only) Compress the resulting archive with compress(1).  In extract or list modes, this option is ignored.  Note that,
             unlike other tar implementations, this implementation recognizes compress compression automatically when reading archives.

Maybe this will not work with GNU tar, I cannot test this at the moment..

Thanks for your quick response.

@Scrutinizer
This works fine for me. The -c option was the solution.

for file in *.tar.gz; do gzip -cd "$file" | tar xf -; done

@RudiC
The tar-command I use does not have a -z option and it won't also be able to recognize a compressed file.