Run script when SSH exits or connection dropped?

I have script in my /etc/profile, this goes and works well when SSh connection is established to the router and then exited from terminal by typing exit, but it fails to run ./finalise script when connection suddenly drops.

if [ -n "$SSH_CONNECTION" ]; then
    ./startup.sh

    trap './finalise.sh' EXIT
fi

Is there anything we can do to run finalise script every time when there is no SSH connections, i.e. last one was dropped/disconnected?

Maybe you can monitor the logread. logread -f|grep -i ssh

that's one of the options I guess. I was looking for event-triggered setup but might be difficult. So for now I am just going ahead with either:

  • cron based approach
    • cons: attempts to run script all the time, even if you don't need it to be run
  • starting another bash background script to validate if there are current SSH connections
    • cons: potentially slightly higher resource use whilst looping compared to cron / pros: script will eventually stop once finalised

Attach screen to last session?