4

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..

1
  • The exit trap does get executed for me when I close the tab.
    – egmont
    Oct 6, 2015 at 21:26

2 Answers 2

3

You want to trap SIGHUP;

From man 7 signal:

SIGHUP        1       Term    Hangup detected on controlling terminal or death of controlling process

So to trap both SIGHUP and EXIT:

trap 'export HISTFILE=/tmp/custom.hist' 1 EXIT

or:

trap 'export HISTFILE=/tmp/custom.hist' SIGHUP EXIT
1

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .