Beginner
Beginner

Reputation: 5467

Trap not activated when calling functions

I am using set -e and a trap handler to produce error messages is my ksh scripts.

#!/bin/ksh
set -e

myexit()
{
    if [[ $1 != 0 ]]; then
         echo "ERROR: Script $0 failed unexpectedly with signal $1!"    
    fi
}

settrap()
{
    for sig in INT TERM EXIT; do
        #echo "setting trap for $sig..."
        trap "code=$?;trap - INT TERM EXIT;myexit $code \"$sig\"; [[ $sig == EXIT ]] || kill -$sig $$" $sig
    done
} 
settrap

Now I have the strange behavior that this works for calling old-style functions, but not for functions calling functions.

test1()
{
    echo "test1"
    eval test2
}

test2()
{
    echo "test2"
    return -1
}

test3()
{
    settrap
    echo "test1"
    eval test2
}

What will happen?

Question: Why does test1 not cause myexit to be called when the call to test2 returns -1?


Edit: The problem is not because functions have local traps. As explained here: Old-style POSIX functions (those created using the name() syntax) share traps with the parent script.

Upvotes: 1

Views: 231

Answers (1)

Beginner
Beginner

Reputation: 5467

The behavior seems to be a bug with signal bubbling in ksh88.

ksh function (not posix) trap not receiving signals -HUP, -TERM but does receive -INT

I switched to using dtksh which is a newer version on my system and everything works fine.

This shebang solves the issue:

 #!/usr/dt/bin/dtksh

Upvotes: 1

Related Questions