Issue
Inside of a bash script, I want to define a function to do the following:
- invoke a sub-program (/usr/sbin/i2sget)
- if the sub-program succeeds, echo what it printed to stdout
- if the sub-program fails, suppress stderr and print "SUPPRESSED" on stdout
Here's what I have that doesn't quite work. (Note: i2sget returns a '0' on success and '2' on a read error):
read_i2s_register () {
local RESULT=`/usr/bin/i2sget -y 1 0x55 0x08`
if [ $? -eq 0 ]: then
echo ${RESULT}
else
echo "SUPPRESSED"
fi
}
When /usr/bini2sget
succeeds, the above function properly echoes its stdout (captured in ${RESULT}.
But when it fails, it prints "Error: Read failed" (presumably on stderr) and it doesn't print SUPPRESSED on stdout.
What's the right way to accomplish the desired behavior?
Solution
The exit code check won't work when you add local
because that has its own exit status that masks whatever the command exited with. To address this, you have to separate the two pieces:
local RESULT
# change 2>/dev/null to 2>&1 if you want
# stderr captured in the RESULT
RESULT=$( /usr/bin/i2sget -y 1 0x55 0x08 2>/dev/null )
if [[ $? -eq 0 ]] ; then
echo "$RESULT"
else
echo SUPPRESSED
fi
Or a little more succinctly to avoid an antipattern:
local RESULT
# change 2>/dev/null to 2>&1 if you want
# stderr captured in the RESULT
if RESULT=$( /usr/bin/i2sget -y 1 0x55 0x08 2>/dev/null ) ; then
echo "$RESULT"
else
echo SUPPRESSED
fi
Answered By - tjm3772 Answer Checked By - Senaida (WPSolving Volunteer)