Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Catch `setopt nounset`



On Apr 9,  6:30pm, Thorsten Kampe wrote:
} 
} I'd to catch the call of a parameter that does not exist with `setopt 
} nounset`.

    setopt nounset
    {
      print "$DOESNOTEXIST"
    } always {
      if (( TRY_BLOCK_ERROR ))
      then print "error"
      else print "no error"
      fi
    }

} If I replace the `catch` statement with `if result=$(testfunc)` it 
} prints "error". What am I missing here? Why does the latter work but 
} not the former?

"parameter not set" is a fatal error, so whatever the current shell is
doing is stopped when that happens.  $(testfunc) is run in a subshell,
so the current shell proceeds even though the subshell died.

You could get the same result with

  if ( testfunc )
  then
    printf "no error\n"
  else
    printf "error\n"
  fi

but of course that also suppresses all other side-effects of "testfunc",
which the "always" construct will not.



Messages sorted by: Reverse Date, Date, Thread, Author