1

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?

  • test1 will exit but not call myexit
  • test2 and test3 will call myexit.

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.

Beginner
  • 5,277
  • 6
  • 34
  • 71
  • 2
    Traps are local to function, that's probably why. Please see : https://docstore.mik.ua/orelly/unix3/korn/ch08_04.htm section 8.4.1. Hope it helps – Andre Gelinas Sep 11 '18 at 17:00
  • 1
    You have a quoting problem in the settrap function: you appear to be expecting `$sig` to be expanded within single quotes. – glenn jackman Sep 11 '18 at 19:08
  • 1
    @AndreGelinas Old-style functions do not share that behavior with the new syntax. – Beginner Sep 12 '18 at 06:33
  • @Beginner but doesn't that mean that `$sig` will be expanded to its current value at expansion-time, which will always be `EXIT` after the loop has completed? The string can't capture the current value at trap-setting-time. – amon Sep 12 '18 at 07:54
  • @amon fixed the quotes – Beginner Sep 12 '18 at 08:02
  • @glennjackman you were right all along. – Beginner Sep 12 '18 at 08:02

1 Answers1

1

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
amon
  • 57,091
  • 2
  • 89
  • 149
Beginner
  • 5,277
  • 6
  • 34
  • 71