Shell – Check if file is an archive; if yes, extract

7zarchivefilesscriptingshell-script

How can I check if a file is an archive and then extract it with 7z? I understand that I could check it by file command but it won't work in scripts because of its output. I can't predict what type of archive it could be. I just want to do something like:

Can I extract it by 7z?
If yes, extract,
if not, go further

by bash sript.

Best Answer

The 7z utility returns a non-zero exit code if the operation it performs fails. You can use this fact to try to extract the archive and then do something else if that fails:

if ! 7z e filename 2>/dev/null; then
    # do something else
fi

or, depending on what else you want to do, or not do,

if 7z e filename 2>/dev/null; then
    exit
fi

# do something else

which may be shortened to

7z e filename 2>/dev/null && exit

# do something else

You could obviously wrap this in

if 7z t filename; then

fi

and catch a failure of extraction (due to not enough disk space or whatever other error might occur during extraction) separately from a failure of determining that this is indeed a 7z archive.

The full code may look like

if 7z t filename 2>/dev/null; then
    if 7z e filename 2>/dev/null; then
        echo 'All is good, archive extracted' >&2
    else
        echo 'Archive failed to extract' >&2
    fi
else
    echo '7z failed to process the file' >&2
fi
Related Question