Bash traps - while emitting ERR trap

From: Andrew DeFaria (Andrew_at_DeFaria.com)
Date: 07/30/03


Date: 30 Jul 2003 14:59:50 -0700

Given the following script:

#!/bin/bash
function cleanup {
  echo "ENTER cleanup"
} # cleanup

trap cleanup EXIT ERR

declare -i i=4

echo "Entering while loop"

while [ $i -gt 0 ]; do
  echo "In while loop"
  let i=i-1
done

echo "Outside while loop"

Why is "ENTER cleanup" echoed twice when run?

$ traptest
Entering while loop
In while loop
In while loop
In while loop
In while loop
ENTER cleanup
Outside while loop
ENTER cleanup

If I remove the EXIT from the trap statement then I get the following

Entering while loop
In while loop
In while loop
In while loop
In while loop
ENTER cleanup
Outside while loop

and if I omit the ERR from the trap statement I get the following:

Entering while loop
In while loop
In while loop
In while loop
In while loop
Outside while loop
ENTER cleanup

It seems as though the EXIT trap is getting invoked properly when the
script exits but the ERR trap is being generated upon exit of the
while loop. Is this correct behavior? If is it correct behavior then
how can I script a cleanup routine to trap properly for such things as
EXIT and ERR in the presence of while loops?

Please email to ADeFaria@Salira.com as I do not regularly read this
newsgroup



Relevant Pages

  • Re: [opensuse] Quick bash question - testing for the presence of keyboard input without pausing
    ... I would like to write a bash routine that tests for the presence of a user keypress to exit a loop from within the loop without stopping the loop to wait like with read. ... catcher using the built-in command trap ...
    (SuSE)
  • Re: Why is GOTO bad?
    ... I prefer BASIC's EXIT DO rather than BREAK as that means you can do ... Ideally there should be some way to optionally label a loop ... Sub DoSomething ... 'add appropriate error handling to ensure cleanup gets called. ...
    (microsoft.public.vb.general.discussion)
  • Re: Bash traps - while emitting ERR trap
    ... >> trap cleanup EXIT ERR ... >> while loop. ...
    (comp.unix.shell)
  • Re: Failing DC
    ... If you are sure that no need for the old DC is anymore you can start to cleanup. ... time being without any issues while I perform metadata cleanup? ... Reboot loop can be virus/spyware etc. also. ... Also need to restore local Administrator and/or Directory ...
    (microsoft.public.windows.server.active_directory)
  • Re: Control-C behavior
    ... look at using a trap.. ... exit - you can set whatever value you want but i chose 11. ... for loop and then set the default trap value for a signal 2. ... When I hit Control-C, I want the top-level script to ...
    (comp.unix.shell)