Comment

Comment by o11c

FWIW, I've grown the following which handles a few more cases. For some reason I wasn't aware of `caller` ...

    set -e

    is-oil()
    {
        test -n "$OIL_VERSION"
    }

    set -E || is-oil

    trap 'echo "$BASH_SOURCE:$LINENO: error: failure during early startup! Details unavailable."' ERR

    magic_exitvalue=$(($(kill -l CONT)+128))

    backtrace()
    {
        {
            local status=$?
            if [ "$status" -eq "$magic_exitvalue" ]
            then
                echo '(omit backtrace)'
                exit "$magic_exitvalue"
            fi
            local max file line func argc argvi i j
            echo
            echo 'Panic! Something failed unexpectedly.' "(status $status)"
            echo 'While executing' "$BASH_COMMAND"
            echo
            echo Backtrace:
            echo
            max=${#BASH_LINENO[@]}
            let max-- # The top-most frame is "special".
            argvi=${BASH_ARGC[0]}
            for ((i=1;i<max;++i))
            do
                file=${BASH_SOURCE[i]}
                line=${BASH_LINENO[i-1]}
                func=${FUNCNAME[i]}
                argc=${BASH_ARGC[i]}
                printf '%s:%d: ... in %q' "$file" "$line" "$func"
                # BASH_ARGV: ... bar foo ...
                # argvi          ^
                # argvi+argc             ^
                for ((j=argc-1; j>=0; --j))
                do
                    printf ' %q' ${BASH_ARGV[argvi+j]}
                done
                let argvi+=argc || true
                printf '\n'
            done

            if true
            then
                file=${BASH_SOURCE[i]}
                line=${BASH_LINENO[i-1]}
                printf '%s:%d: ... at top level\n' "$file" "$line"
            fi
        } >&2
        exit "$magic_exitvalue"
        unreachable
    }
    shopt -s extdebug
    trap 'backtrace' ERR
parent o11c 1 year ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton