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.
try() { "$@" || ! echo "$1 returned $?" >&2 || exit; }
set -e
.eval
does. It is something you need to be careful with.