Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a bash script that creates a '.tar' file. Once the file is created, I would like to test its integrity and send an email to the root user if the integrity is bad.

I know I would need to use the command tar -tf /root/archive.tar to check the integrity of the file, but how would I implement this in a bash if statement and check for errors?

share|improve this question

2 Answers 2

If tar finds errors in its input it will exit(3)¹ with a non-zero exit value. This — with most tar implementations — is also done when listing archive contents with t. So you could simply check for the exit value of tar to determine if something has gone wrong:

if ! tar tf /root/archive.tar &> /dev/null; then

If your tar does not find all errors with t, you could still extract the archive to stdout and redirect stdout to /dev/null, which would be the slower but more reliable approach:

if ! tar xOf /root/archive.tar &> /dev/null; then

¹ This notation denotes the manpage, not the actual call. See man 3 exit.

share|improve this answer
You'll probably want to redirect the tar output to /dev/null, as you probably don't actually want to see it. –  Kevin May 16 '14 at 4:09
Not all tar implementations detect or report all errors with t (bsdtar doesn't, you can use tar xOf file.tar > /dev/null there). Not all tar implementations would exit with exit status 2, star (255) ot bsdtar (1) don't, but what matters is that the exit status is non-zero here. –  Stéphane Chazelas May 16 '14 at 6:18
I edited my post accordingly. With exit(2) I was regarding to the appropriate manpage, not the exact exit value (which is why I had »non-zero« explicitly mentioned in the following sentence). Annotated this (and changed the section to the right one -.-). –  Andreas Wiese May 16 '14 at 14:50

You can do it by passing the following arguments to tar:

$ tar -cvzf test.tar test_file
share|improve this answer
One-line answers are often not that helpful. Consider expanding your post to include some source material (e.g., documentation) that supports your solution. –  HalosGhost Aug 7 '14 at 5:56

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.