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:or, depending on what else you want to do, or not do,
which may be shortened to
You could obviously wrap this in
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