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.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

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
-c creates the file named via -f ('test.tar'). -z gzips the archive. -v makes it verbose. I'm pretty sure this is not an accurate solution. – Peg Leg 3941 Dec 28 '15 at 5:07

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.