2

When running the following script in OSX using bash version 3.2

#!/bin/sh

set -e
function _trap_exit {
   echo "this is a triggered trap..."
}

trap _trap_exit EXIT

/usr/sbin/ioreg -w0 -l | grep ExternalChargeCapable | grep -q No

echo "Final statement"

I get a trap triggered. But if I change the final grep statement to Yes ie grep -q Yes then the trap isn't triggered.

Any idea why this is happening and how to stop it? Why should the exit code from grep cause a trap to be triggered?

closed as off-topic by cuonglm, Anthon, chaos, Stephen Kitt, dhag Oct 5 '15 at 14:40

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions describing a problem that can't be reproduced and seemingly went away on its own (or went away when a typo was fixed) are off-topic as they are unlikely to help future readers." – cuonglm, Anthon, chaos, Stephen Kitt, dhag
If this question can be reworded to fit the rules in the help center, please edit the question.

  • You use EXIT signal, the trap will always be triggered. – cuonglm Oct 5 '15 at 11:59
  • @cuonglm You are corrent that at the end the script will always always trigger the EXIT trap, unfortunately in the case above it was before the script ended. It was the set -e which I had copy/pasted which caused the the problem... See my answer... – Vic Oct 5 '15 at 12:04
2

From Bash man page...

-e      Exit immediately if a simple command (see SHELL GRAMMAR above) exits with a non-
        zero  status.   The shell does not exit if the command that fails is part of the
        command list immediately following a while or until keyword, part of the test in
        an  if  statement,  part of a && or || list, or if the command's return value is
        being inverted via !.  A trap on ERR, if  set,  is  executed  before  the  shell
        exits.

[/Slapshead]

Sorry to have wasted your time...

Not the answer you're looking for? Browse other questions tagged or ask your own question.