user1165758
user1165758

Reputation: 1

Capture stderr into a pipe from command expansion

I have a program that returns answers on stdout and errors on stderr. Unfortunately the program ends by emitting some text on stderr even if successful.

I would like to store the program output in a variable using command expansion as: ans=$(prog) 2>&1 | grep -v success

This doesn't work. Tried putting 2>&1 in the parens, but as I suspected $ans then gets the success text.

Any ideas?

Upvotes: 0

Views: 145

Answers (1)

praetorian droid
praetorian droid

Reputation: 3029

Not sure, what you trying to get, but probably this is your command:

ans=$(prog 2>&1 | grep -v success)

If you want to filter 'success' only from standard error stream, you could use something like this:

ans=$({ ./foo 3>&2 2>&1 >&3- | grep -v success; } 2>&1)

And just in case, as noted in BashFAQ/002:

What you cannot do is capture stdout in one variable, and stderr in another, using only FD redirections. You must use a temporary file (or a named pipe) to achieve that one.

Upvotes: 2

Related Questions