I actually had a similar question recently (though I didn't post, I got around to it), and, from what I can see, it seems like just using set +e before the command and set -e afterward works most elegantly. Here's an example, grabbing the response of the command and not letting the error throw it away.
#!/bin/sh
args=""
for argcol in $*
do
args="${args} ${argcol}"
done
fortunevar=""
fortfail=""
{
set +e
fortunevar=`fortune $args`
fortfail=$?
set -e
} &> /dev/null
if [ $fortfail == 0 ]
then
echo ${fortunevar}
say ${fortunevar}
else
echo misfortune: an illegal option was detected!
echo misfortune: usage: misfortune [-afilosw] [-m pattern][ [#%] file/directory/all]
fi
This grabs the output of 'fortune', checking its exit status, and echoes and says it. I think this is what you were asking for, or at least something similar? Anyway, hope this helps.
set -e
Uncomment next line to see set -e effect:
#blubb
if blubb; then
– Gustave Jul 14 '15 at 16:20echo "Command blubb was succesful."
else
echo "Command blubb failed. Exit code: $?"
fi
echo normal script exit
set -eon it (e.g. depends on execution context, like a command line param tobash, decided by the user), then this will force-fully, always, in every context, enableset -eafter the "bad" command. – TWiStErRob Aug 28 '22 at 21:14