Re: Bash traps - while emitting ERR trap

From: Michael Wang (mwang_at_unixlabplus.com)
Date: 07/31/03


Date: Wed, 30 Jul 2003 23:23:42 GMT

In article <b66bb9ae.0307301359.14f19114@posting.google.com>,
Andrew DeFaria <Andrew@DeFaria.com> wrote:
>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
 
bash must think "0 < 0" is an error condition, and
envoked the error trap. This is incorrect behavior.

>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
 
Same explanantion as above.

>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
 
This is correct.

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

No. I do not think it the while loop per se. I think if you use

if (( 1 == 2 )); then echo no; fi

it will envoke the err trap. Unfortunately, I have bash is too old
to support err trap (version 2.05), and a version too new to have the
problem (2.05b). So I think you must have 2.05a.

>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?
 
Serveral options:

(1) downgrade to 2.05 so that err trap can not be used
(2) upgrade to 2.05b so that there is no such a problem
(3) upgrade to ksh93

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

Posted and emailed.

-- 
Michael Wang * http://www.unixlabplus.com/ * mwang@unixlabplus.com


Relevant Pages