Operating System - HP-UX
1826507 Members
3159 Online
109693 Solutions
New Discussion

trap not working as expected

 
fam
New Member

trap not working as expected

Below is the prototype of the script I am using -

==============================================
function1
{ typeset -i ERR=0
trap return ${ERR} ' 2 3 15 '
#some commands modify the value of ERR #
}

funtion2
{ typeset -i ERR=0
trap return ${ERR} ' 2 3 15 '
#some commands modify the value of ERR #
}


menu ()
{ select in item 'item1' 'item2'
do
case $REPLY in
1 )
function1
echo $? ;;
2 )
function2
echo $? ;;
esac
done
}

menu

=============================================

The expected - >

Whenever a INT signal is recieved when the the script is inside function1 or function2, the trap code should execute which is a return statement. Thus control control should pass to calling function i.e. menu

The actual - >

the function ( function1 or function2 ) continues to execute from the line next to the one where interrupt was recieved !!

Can someone please help me to achieve 'The expected '
3 REPLIES 3
Tim Nelson
Honored Contributor

Re: trap not working as expected

What if you placed the trap outside of the function ?

#!/usr/bin/ksh
trap "echo 'interrupt...';menu" 2
function1()
{
echo function1
read yorn
echo "user chose enter"
}
function2()
{
echo function2
read yorn
echo "user chose enter"
}

menu()
{
select option in function1 function2 exit
do
case "$option" in
function1) function1;;
function2) function2;;
exit) echo "exiting...";exit ;;
esac
done
}
menu
James R. Ferguson
Acclaimed Contributor

Re: trap not working as expected

Hi:

Aside from some syntax errors like no keyword 'function' before the function name; and a syntactically incorrect 'select' [ it should be "select item in ..." ], you need to rethink your approach.

From the 'sh-posix' manpages, "traps remain in effect for a given shell until explicitly changed with another trap command; that is, a trap set within a function will remain in effect even after the function returns."

I would globally trap and ignore signals 2, 3 and 15 and let your functions 'return' values that are otherwise meaningful to the calling block.

Regards!

...JRF...

Re: trap not working as expected

Hello,

You should surround the command to be executed with quotes (actually double quotes to allow the shell substituting $ERR) instead of the signal numbers :

trap "return $ERR" 2 3 15

Cheers,

Jean-Philippe