0

I want to do 2 things with a tar.gz file:

  1. Check for failure
  2. If successful - check number of files extracted

I found this for the 1st option. I now run my command like this: tar -xvzf bad_file.tar.gz && echo ok || echo fail and it echos all the errors + fail at the end, which is what I want.

For the 2nd part, I used to use tar -xvzf bad_file.tar.gz | wc -l which worked fine, but returned number of files, even if an error occurred.

Example for the 2nd part (I opened the file in an editor and just removed a line):

[root@zt avi]# tar -xvzf damaged_file.tar.gz | wc -l

gzip: stdin: invalid compressed data--crc error

gzip: stdin: invalid compressed data--length error
tar: Unexpected EOF in archive
tar: Unexpected EOF in archive
tar: Error is not recoverable: exiting now
3

How can I combine these 2 commands?

1 Answers1

1

Test the extraction of the archive separately, then count the number of files if it succeeded. If you don't know the name of the directory that the archive extracts into, create a new directory and extract the archive in there. Maybe something like this:

#!/bin/sh

if [ -d extracted ]; then
    echo 'please remove directory "extracted"' >&2
    exit 1
fi

mkdir extracted
if ! tar -xvz -f bad_file.tar.gz -C extracted; then
    echo 'extraction failed' >&2
    echo 'directory "extracted" may contain partially extracted archive' >&2
    exit 1
fi

# extraction of archive was successful, count files extracted
find extracted -type f -exec echo . ';' | wc -l

The find at the end outputs a dot for each file in the extracted directory. wc -l counts the number of dots. We do it this way in case a pathname in the extracted directory contains an embedded newline.

Kusalananda
  • 333,661