My script calls an external command (e.g. readlink
) which will either:
- write a useful string to its stdout on success, or…
- return a non-zero exit status on failure
I know how to do each individually, e.g. to capture the stdout I can use
MY_VAR=$(readlink /)
Or to check the result I could use:
if readlink /tmp; then
echo "Success"
fi
But is there a clean/clear way to do both ± simultaneously? I'm not sure the following would work:
if MY_VAL=`readlink "$MY_ARG"`; then
echo "Value is ${MY_VAL}"
else
echo "Not found"
fi
UPDATE: so I tried that, and it did work. But is it only a coincidence, e.g. happens to work because readlink's output is empty at the same time it errors?
As a particular constraint, I need to do this in an environment where set -e
is specified, i.e. if other commands return an error the overall script will fail. Generic shell preferred, unless bash has a better mechanism.