For example: I extract a tar.bz2 file with tar -xvf instead of tar -xjvf:

 tar -xvf file.tar.bz2
 tar: invalid tar magic

and if redirect stderr

 tar -xvf file.tar.bz2 2>/dev/null

it works.

Now if I use a pipe

 tar -xvf file.tar.bz2 | grep "something" 2>/dev/null 
 tar: invalid tar magic

Here if the first command fails I cannot suppress the error.

Is there a way to suppress in this way

  • Not sure what you mean by "it works". Note that ignoring this error won't "solve" the problem... The reason you're getting the error is that the *.bz2 file is not a tar file so the type-check (tar magic code at the beginning) fails. Also a grep on stdout won't actually search the contents of the extracted files. Can you explain what are you trying to achieve here? – arielf Sep 9 '15 at 7:36

Here are couple of alternatives that involve redirecting STDERR of both tar and grep :

  • Use bash command grouping {}:

    { tar -xvf file.tar.bz2 | grep "something" ;} 2>/dev/null
  • Using a subshell () :

    ( tar -xvf file.tar.bz2 | grep "something" ) 2>/dev/null

Note that if you want to redirect STDERR of a single process its better to use Oli's answer instead.

On a different note, if you want to grep something over both the STDOUT and STDERR of tar use :

tar -xvf file.tar.bz2 |& grep "something"

This will also cause the STDERR of tar to be exhausted.

This is actually a shorthand for :

tar -xvf file.tar.bz2 2>&1 | grep "something"

The pipe forms a separate clause in the command so the redirection in...

tar -xvf file.tar.bz2 | grep "something" 2>/dev/null 

...is redirecting the STDERR from grep, not tar.

To fix, simply reorder things so your redirect is with your tar command:

tar -xvf file.tar.bz2 2>/dev/null | grep "something"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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