tmux – How to Execute Cleanup Command on Server/Session Exit

command linesession-managersession-restoretmux

To improve my workflow a little I have written a few wrapper scripts to automatically start some commands when I want to work on a project. When I'm done however, and clean all the tmux tabs for this specific session I would like to kill some processes and cleanup some files.

Is there any way to automatically execute a command when exiting the tmux server?

The wanted workflow:

  • execute command to create new tmux server, open some files, start a few apps
  • work in the session
  • detach to work on it later
  • reattach
  • when all tabs in the tmux server are closed and the server is destroyed, execute a cleanup command

[edit]The script I currently use: https://github.com/WoLpH/dotfiles/blob/master/bin/tmx

Best Answer

For now, there is no specific way to have tmux automatically run commands triggered by detach or closing all windows in the session. However, since you already have a wrapper script (I will call this tmux_wrapper) that opens your desired custom-session, you can easily convert this script to automate cleanup. I do something very similar to this myself here, where I wanted to allow nested tmux sessions if I am attaching through ssh.

Since you have a custom experience in mind, you no longer need the tmux attach .... or similar commands, so I will assume you always start session for project A by something like tmux_wrapper A. In your wrapper you probably have a line similar to tmux new-session -s A. Here we can take advantage of the session name A. Then, at the end of your wrapper you can have a cleanup switch that only activates if the session is no longer live (i.e. windows/panes are no longer attachable).

A simple example tmux_wrapper would look something like this:

#!/bin/sh

sess=$1

# test if the session has windows
is_closed(){ 
    n=$(tmux ls 2> /dev/null | grep "^$sess" | wc -l)
    [[ $n -eq 0 ]]
}

# either create it or attach to it
if is_closed ; then
  tmux new -s $sess
else
  tmux attach -t $sess
fi

# the session is now either closed or detatched
if is_closed ; then
    # perform cleanup here ...
fi

Run it like tmux_wrapper A. Now, the cleanup will automatically occur for session A if and only if the session has been completely closed.

Related Question