Sometimes I ssh into a box, and run some script that makes a change to the system. I want to undo this change when my session ends, either explicitly (e.g., via exit from the logout shell) or implicitly (e.g., because my ssh session times out).

Can I set up something that will accomplish this?

As a strawman example, assume I create a file /etc/foo and at the same time I want to register a cleanup script which does a rm /etc/foo at some point when my ssh session ends.


Two ways:

If you want to do a one-off thing, you can set an EXIT trap:

trap 'rm /etc/foo' EXIT

This would run the given code when the current shell exits. The trap could be set at the interactive prompt, or in $HOME/.bash_profile if you want to make it something that happens each time (note that setting the trap again would remove a previously set trap). You may remove the trap before it is executed with trap - EXIT.

Another way would be if you want to always run a particular set of commands when an interactive login shell exits, you may put those commands in $HOME/.bash_logout.

This file is executed when an interactive login shell exits, or when a non-interactive login shell executes exit.

  • Thanks! Imagine that sometimes I run a script, make_foo.sh, which creates the file, and only if this script is run do I set up the cleanup. This seems to make the trap a bit harder, because the trap would apply to the current script, not the logon shell. I guess I could require that the script is run with source, but that seems error prone? – BeeOnRope Jul 17 at 15:36
  • 1
    @BeeOnRope It depends, you could use rm -f /etc/foo which would not complain if the file did not exist, and then always run the cleanup. This would work if the file never need to exist after logging out. Or, you could make your script create a /tmp/do_cleanup file that your logout code detects, and then does the cleanup (if that file exists). It really depends on what you want and are able to do. In any case, I've given you a couple of avenues for executing arbitrary code upon logout. – Kusalananda Jul 17 at 15:40

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.