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; }– mikeserv Sep 09 '14 at 11:29set -e. – phemmer Sep 09 '14 at 12:46evaldoes. It is something you need to be careful with. – mikeserv Sep 09 '14 at 13:53evalworks here. There are probably far better references on the subject out there, but I had a link to this one... – mikeserv Sep 09 '14 at 14:04