M BUZZ CRAZE NEWS
// general

How to suppress tar error messages in when piping

By Gabriel Cooper

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

1

2 Answers

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"
0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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