All shells have a way to run some code when the shell exits: a trap. “Trap” is the shell word for signal handler. You can set a trap for a signal by listing its name (
HUP, …) or its number, or use the special value
EXIT for when the shell exits normally (by reaching the end of the input or if
exit was called).
trap 'echo "$IP_ADDRESS logged out at $(date)" >>"$LOG_FILE"' EXIT HUP INT TERM
You can't trap
kill -KILL or power failures.
I doubt that what you're doing is actually useful. This information is already recorded in the system logs. It's even more reliable there, because you get an entry for
kill -KILL too. The command
last shows the start date, end date and origin (terminal or IP address) for all past and current sessions since the last log rotation.