-2

I created a script which will extract all *.tar.gz file. This file is decompressed five times .tar.gz file, but the problem is that only the first *.tar.gz file is being extracted.

for file in *.tar.gz; do
        gunzip -c "$file" | tar xf -
done
rm -vf "$file"

What should I do this? Answers are greatly appreciated.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user3534255
  • 137
  • 1
  • 3
  • 14
  • 2
    Please reword your question, it is hard to understand what you're asking. If your problem is that only one file is getting deleted after the decompression, that is because your `rm -vf` statement is outside of your for loop. It needs to come before `done`. – savanto May 07 '14 at 02:30
  • My question is about extracting the the tar.gz file it is decompressed 5 times and the problem is I only extracted it once. The loop must extract all the tar.gz file – user3534255 May 07 '14 at 03:00
  • So, you have 5 `.tar.gz` files in the directory when you start; you run the script shown with its loop; and it extracts the same file 5 times rather than 5 files one time each? What happens when you run with `bash -x yourscript.sh`? Can you show the output of that? Have you thought of using `tar -xvf -`? Which platform are you on that you need to manually do the `gunzip` — because GNU `tar` handles decompression automatically? – Jonathan Leffler May 07 '14 at 05:22

1 Answers1

4

If your problem is that the tar.gz file contains another tar.gz file which should be extracted as well, you need a different sort of loop. The wildcard at the top of the for loop is only evaluated when the loop starts, so it doesn't include anything extracted from the tar.gz

You could try something like

while true; do
    for f in *.tar.gz; do
        case $f in '*.tar.gz') exit 0;; esac
        tar zxf "$f"
        rm -v "$f"
    done
done

The case depends on the fact that (by default) when no files match the wildcard, it remains unexpanded. You may have to change your shell's globbing options if they differ from the default.

If you really mean that it is compressed (not decompressed) five times, despite the single .gz extension, perhaps you need instead

for i in 1 2 3 4; do
    gunzip file.tar.gz
    mv file.tar file.tar.gz
done
tar zxf file.tar.gz
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • +1, from your answer, I start to understand the OP's question. Maybe your guess is right. – BMW May 07 '14 at 05:41