Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run script before Bash exits

Tags:

bash

exit

xfce

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

like image 789
Facundo Casco Avatar asked Feb 17 '11 19:02

Facundo Casco


People also ask

How do I exit bash script without exiting shell?

If you are executing a Bash script in your terminal and need to stop it before it exits on its own, you can use the Ctrl + C combination on your keyboard.

Do you need to exit a bash script?

Often when writing Bash scripts, you will need to terminate the script when a certain condition is met or to take action based on the exit code of a command.

What is trap exit in bash?

The secret sauce is a pseudo-signal provided by bash, called EXIT, that you can trap; commands or functions trapped on it will execute when the script exits for any reason.

How do I exit bash script early?

One of the many known methods to exit a bash script while writing is the simple shortcut key, i.e., “Ctrl+X”. While at run time, you can exit the code using “Ctrl+Z”.


2 Answers

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.

like image 164
DVK Avatar answered Sep 23 '22 07:09

DVK


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
like image 26
Arturo Herrero Avatar answered Sep 20 '22 07:09

Arturo Herrero