Search code examples
macosbashtestingterminalsignals

Suppress signal output like "Abort trap: 6" in a shellscript, for a test that should crash


Something helpfully outputs Abort trap: 6 when a program crashes, that is started from a bash:

$ ./crash-if-correct > /dev/null 2>&1
Abort trap: 6

For a test case that should be crashing, this creates output that looks wrong. How can this be suppressed ?

I suspect it's not the shell (in my case that's bash), because an ack 'trap:' through the bash sources revealed nothing.

Simple way to reproduce:

$ cat <<EOF > abort.c
main()
{
   abort();
}
EOF

$ cc -w -o abort abort.c
$ sh -c ./abort > /dev/null 2>&1
Abort trap: 6

Solution

  • The solution is to run the child process in a subshell :

    $ cc -w -o abort abort.c
    $ $(./abort)
    $
    

    This works for me on OSX.

    Note that if ./abort outputs text, it will be executed

    $ cat hello-abort.c
    main()
    {
        puts("Hello");
        abort();
    }
    $ cc -w -o hello-abort hello-abort.c
    $ ./hello-abort
    Hello
    Abort trap: 6
    $ $(./hello-abort)
    bash: Hello: command not found                   # <== Danger
    $ exec 3>&1; $(./hello-abort >&3); exec 3>&-
    Hello
    $
    

    In zsh, the return value of the last command is 134. Append || true to the command to make it become 0.

    Credits