Bash – Execute code in a logout script if exiting from a particular directory

bashlogoutshell-script

I have accounts on a number of different machines for testing a couple libraries I contribute to. Some of the machines are owned by others (like the GCC compile farm), and I'd like to keep them tidy.

I want to setup a .bash_logout script that performs a make clean upon exit if I am in a particular directory. The directory requirement drops out of multiple SSH sessions. If I am building/testing in one session, I don't want a separate session logout cleaning the artifacts. That is, exit from $HOME/libfoo performs a clean; while exit from $HOME does not.

I understand the basics, but its not clear to me how robust this is:

# $HOME/.bash_logout

if [ "$PWD" = "$HOME/libfoo" ]; then
    make clean 1>/dev/null 2>&1
fi

Are there any problems with using $PWD during logout? Are there any other problems that I might have missed?

Best Answer

Is your intent to execute the script only on log-out?
From man bash:

When a login shell exits, bash reads and executes commands from the file ~/.bash_logout, if it exists.

Only on exit of a bash login shell.


If you intend to run an script on every shell close, use trap (see man bash):

trap /u1/myuser/on_exit_script.sh EXIT

Add it to .bashrc or some other that works for you.


Also, as the script will execute on exit, the $PWD will be the one active on exit, which may or may not be the same as when the shell was started. If you need to do something on the $PWD that was in use on exit, then yes, this test:

if [ "$PWD" = "$HOME/libfoo" ]; then

Should work.

Related Question