How to Execute Shell Script on Logout

Sometimes I need to run a cleanup script automatically once I logout from a Linux or UNIX system. I normally use the script to cleanup my own temporary files.

Most of the popular Linux or UNIX shells support this. For BASH, the files ~/.bash_logout and /etc/bash.bash_logout are executed when the shell exits. This is valid for other shells like TCSH as well, but the files to be run will be different. For TCSH, the files /etc/csh.logout and ~/.logout will be executed.

If the shell that you are using is old or does not support this functionality (eg. Korn shell), then we will need to perform some workarounds. We will need to modify the shell login initialisation file, which is normally the .profile file residing in your home directory.

Edit the file and append the following line of code at the end of the file.

trap ". $HOME/.shell_logout" 0

What we are trying to do is to trap the SIGCHLD signal which is sent to the parent process of the shell when the shell exits.

Now, open the .shell_logout file and enter your own cleanup commands. Below is my cleanup script that removes all files in the $HOME/tmp directory.

echo "Performing cleanup..."
find $HOME/tmp -type f -exec rm -rf {} \;

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, php, python, java, javascript, nodejs, react); plays_on(xbox, ps4); linux_desktop_user(true); }