CIsForCookies
CIsForCookies

Reputation: 12817

redirecting error to one file and stdout to another function and then another file

I've seen this answer about redirecting stdout / stderr to different places by using command 2>x 1>y. However, I'm interested in manipulating the stdout part:

I want to tar -xvzf a file, count the output files, and store that in a file, and store the errors in another file.

1st attempt:

tar -xvzf pkg.tgz 2>err 1>output

the file names themselves are saved in output (I didn't use wc -l, but at least it gives a meaningful output)

2nd attempt:

tar -xvzf pkg.tgz 2>err 1 | wc -l >output

tar: 1: Not found in archive

tar: Exiting with failure status due to previous errors

How can I get number of files extracted OR failure indication if something went wrong (the tar -xvzf usually unpacks the files AND outputs the error)?

3rd attempt:

tar -xvzf pkg,tgz 2>err | wc -l > output

kind of works, but I'm not sure about it...

My question is: is my 3rd attempt legit? Also, is there an option that the redirection would create a file ONLY if it has data in it (i.e. if stderr has nothing, no err file will be created?)

Upvotes: 1

Views: 140

Answers (1)

Gem Taylor
Gem Taylor

Reputation: 5613

The tee command can help a lot in this situation. It is like a T junction on a road or pipework. Tee takes the std input, sends it to 1 or more files, and then also output to std output, which might have further filters, such as wc.

If you want to do further manipulation on the content before saving it to a file, then do it before the tee. If you want to do extra manipulation just on the file, then in bash, you can use >(command) instead of the filename.

Upvotes: 1

Related Questions