You can use the command substitution
$(..) syntax in the
if condition and see if the command ran successfully or not and still storing the result of the command both
stderr in a variable
if ! var=$(cmd 2>&1); then
printf 'process stderr contents from $var'
You can see it working if I simulate the
cmd to run as a simple script that does this
# cat temp.sh
echo foo >&2
and if I run the script as
if ! var=$(bash tmp.sh 2>&1); then
printf '%s\n' 'process stderr contents from $var'
printf '%s\n' "$var"
The same way you can make it work for capturing
stdout if the command substitution is successful which will happen to be in the
else clause in the above example. In either cases, manipulating the content of
"$var" (ensure the quotes are on) will ensure you are processing the result as if it were stored in a file.
You can further go ahead and quote the command-substitution syntax to not let the shell perform word-splitting on the results. E.g. By doing it as below. It might not be needed for straightforward cases like the one I have showed here, but for cases when the results contain some special shell meta characters
if ! var="$(bash tmp.sh 2>&1)"; then
Note: Question title re-phrased since the first version of the answer has been posted.