21

I'd like to run a script every time I close a Bash session.

I use XFCE and Terminal 0.4.5 (Xfce Terminal Emulator), I would like to run a script every time I close a tab in Terminal including the last one (when I close Terminal).

Something like .bashrc but running at the end of every session.

.bash_logout doesn't work

Arturo Herrero
  • 12,772
  • 11
  • 42
  • 73
Facundo Casco
  • 10,065
  • 8
  • 42
  • 63

4 Answers4

24

You use trap (see man bash):

trap /u1/myuser/on_exit_script.sh EXIT

The command can be added to your .profile/.login

This works whether you exit the shell normally (e.g. via exit command) or simply kill the terminal window/tab, since the shell gets the EXIT signal either way - I just tested by exiting my putty window.

DVK
  • 126,886
  • 32
  • 213
  • 327
11

My answer is similar to DVK's answer but you have to use a command or function, not a file.

$ man bash

   [...]

   trap [-lp] [[arg] sigspec ...]
          The command arg is to be read and executed when the shell
          receives signal(s) sigspec.

          [...]

          If a sigspec is EXIT (0) the command arg is executed on
          exit from the shell.

So, you can add to your .bashrc something like the following code:

finish() {
  # Your code here
}

trap finish EXIT
Community
  • 1
  • 1
Arturo Herrero
  • 12,772
  • 11
  • 42
  • 73
3

Write you script in "~/.bash_logout". It executed by bash(1) when login shell exits.

jellyfish
  • 596
  • 1
  • 7
  • 9
  • Note that this only works if bash is executed as a login shell, e.g. if you login via SSH or check "Run command as a login shell" in gnome-terminal's Profile Preferences. – Splitlocked Jan 05 '15 at 10:41
1

If you close your session with "exit", might be able to something like alias endbash="./runscript;exit" and just exit by entering endbash. I'm not entirely sure this works, as I'm running windows at the moment.

edit: DVK has a better answer.

gailbear
  • 519
  • 3
  • 13