Bash – Shell script error handling while assigning STDOUT to variable

basherror handlingshell-scriptvariable

I am trying to implement error handling in my shell script as described in the 2nd answer in Best practice to use $? in bash?

My script looks like this:

#!/bin/bash

try() {
    "$@"
    code=$?
    if [ $code -ne 0 ]
    then
        echo "oops $1 didn't work"
        exit 1
    fi
}

try myvar=$(mktemp -p ./)

The script exits with a

./test.sh: line 4: myvar=./tmp.scNLzO1DDi: No such file or directory
oops myvar=./tmp.scNLzO1DDi didn't work

Just,

myvar=$(mktemp -p ./)

of course works fine, and $myvar returns the full path and name of the temp file.

How can I get the statement to assign the name of the tmp file to the variable myvar, while still passing the entire statement and it's results to try() so try() can do what it needs to? Thanks.

Best Answer

I think you want to use an error trap instead of a wrapper around evaluation.

err_handler () {
    code=$?
    if [ $code -ne 0 ]
    then
        echo "oops $1 didn't work"
        exit 1
    fi
}

trap 'err_handler' ERR
myvar=$(mktemp -p ./)
trap ERR
Related Question