I can trap the exit command from a gnome-terminal window using the
Bash trap command, but it only works if the user types exit in the terminal window. If the user clicks the close button instead, the trap exit handler is not executed.
Background information:I would like to save Bash history to a custom history file when the user clicks the close button. I have used export HISTFILE=/tmp/custom.hist, this works in many cases (when the user clicks the close button in the gnome-terminal, the history is saved to the given file), but in some cases the history is not saved, so I am looking for alternatives to setting the HISTFILE environment variable..
2 Answers
You want to trap SIGHUP;
From man 7 signal:
SIGHUP 1 Term Hangup detected on controlling terminal or death of controlling processSo to trap both SIGHUP and EXIT:
trap 'export HISTFILE=/tmp/custom.hist' 1 EXITor:
trap 'export HISTFILE=/tmp/custom.hist' SIGHUP EXIT You could save the history file after every command. This trick is usually used to synchronize the history for multiple windows, but would work in your case. See for example, this answer