3

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?

2
  • You use EXIT signal, the trap will always be triggered. Commented Oct 5, 2015 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... Commented Oct 5, 2015 at 12:04

1 Answer 1

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...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.