Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter stderr AND get initial return code

Tags:

shell

ksh

Within a shell script I must run a command for which I need to determine what the return code is, but it turns out the output of the command goes to stderr AND also outputs the user's password (a parameter to the command unfortunately; bad, I know).

I would at least like to filter the passwd from being displayed back.

cmd ${OPTIONS}
RETURNCODE=$?

gives me the return code of the command

cmd ${OPTIONS} 3>&1 1>&2 2>&3 | sed "s:${PASSWD}:******:"
RETURNCODE=$?

Successfully filters the PASSWD but the return code is always 0 - that of the the sed, not the initial command.

Any tricks ?

like image 266
Ian W Avatar asked Aug 11 '26 00:08

Ian W


1 Answers

There are several techniques. In bash, you can check the array PIPESTATUS. For a portable solution, you can do things like:

RETURNCODE=$({ { cmd $OPTIONS 3>&1 1>&2 2>&3; echo $? >&4; } | sed ... >&2; } 4>&1 )

This has the nice side-effect of retaining the behavior of cmd, and the output of sed goes to stderr in the same way that the output of cmd does. (Whether or not that is actually desirable is a different question!)

like image 92
William Pursell Avatar answered Aug 14 '26 06:08

William Pursell