Issue
I'm trying to capture the stderr of a subcommand, my idea is something like this:
subErr(){
echo "${1}"
exit 1
}
BLOB=$(some long command || subErr $2)
aws configure set x_security_token_expires $(echo $BLOB|jq -r '.Credentials.Expiration') --profile DEFAULT
So basically if the command fails, feed the stderr to a function which prints the error and exits.
If the command succeeds assign stdout to BLOB and continue processing
How can I achieve this?
Solution
How about saving stderr to a file for later consumption by your function:
errFile=$(mktemp) || exit
trap 'rm -f "$errFile"; exit' 0
subErr(){
cat "$errFile"
exit 1
}
BLOB=$(some long command 2>"$errFile") || subErr
You could redirect all stderr to the same file with exec 2>"$errFile"
so you don't need to add that to each command call but idk if you want to do that for all stderr output.
Alternatively, see redirect-stderr-and-stdout-to-different-variables-without-temporary-files where I particularly like:
{
IFS= read -rd '' err
IFS= read -rd '' out
IFS= read -rd '' status
} < <({ out=$(ls /dev/null /x); } 2>&1; printf '\0%s' "$out" "$?")
which you'd have to massage to suit your needs.
Answered By - Ed Morton Answer Checked By - Katrina (WPSolving Volunteer)