#!/bin/bash

export TOP_PID=$$
trap 'exit 1' TERM

exit_script(){
    kill -s TERM $TOP_PID
}

echo "before exit"
:|exit_script
echo "after exit"
EOF

  执行结果为

before exit