5

I want to execute a specific sh script when closing a terminal.

I edited the .bash-logout file, added this line of code inside if statement

[ -x /home/user/Documents/logout_msg.sh ] && /home/user/Documents/logout_msg

I made logout_msg.sh executable, and also outside of if statement I added basic echo message with sleep command after, but this is not showing when closing the terminal.

What might be the problem?

2
  • When should it be executed? Before the terminal closes or after? If after, are you expecting to be able to see anything? And how would you close the terminal? Using the mouse or with exit or Ctrl+D?
    – terdon
    Apr 4, 2018 at 15:43
  • It should be executed after closing terminal with mouse or exit command Apr 4, 2018 at 15:45

1 Answer 1

5

The ~/.bash_logout file is only sourced when you exit a login shell (from man bash):

When an interactive login shell exits, or a non-interactive login shell executes the exit builtin command, bash reads and executes commands from the file ~/.bash_logout, if it exists.

When you open a terminal, you are running an interactive non-login shell, so ~/.bash_logout is not relevant. For more on the different types of shell, see my answer here.

In order to have something executed each time you close the terminal, you could use trap to set a command to run every time an interactive bash session exits. To do this, add this line to your ~/.bashrc:

trap /home/user/Documents/logout_msg.sh EXIT 

Of course, if that script is printing a message to the terminal, you need to make sure your logout_msg.sh includes a sleep command so the user will have time to read the message. Something like:

echo "Whatever message you want"
sleep 10 ## wait for 10 seconds
5
  • The actual goal is to execute sh script which will clear history then show time spend in terminal after delay 5 secs and it will close Apr 4, 2018 at 15:48
  • @ViktorSokolov then this should work. See update. Just add a sleep call inside the logout_msg.sh script.
    – terdon
    Apr 4, 2018 at 15:53
  • Thank You! What about if I want to close it with a mouse? Apr 4, 2018 at 15:57
  • i used SIGHUP command alongside with EXIT but this didn't work Apr 4, 2018 at 16:11
  • @ViktorSokolov I don't think it will be possible with a mouse. That kills the terminal GUI process, which is the parent process of the bash shell. That has nothing to do with bash itself. You would somehow have to capture the mouse click on the X and have it do something different. I really doubt it will be possible (I mean, it will be possible, but very very complicated).
    – terdon
    Apr 4, 2018 at 16:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.