Ubuntu – execute script when closing terminal

bashcommand linescripts

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?

Best Answer

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
Related Question