9

Is there a way to update tmux window attributes based on command exit status? Similar to activity monitoring, I would like the title to change color when a command exits, say, green for success and red for failure. I've hacked something together using PROMPT_COMMAND (which goes in ~/.bashrc), but it's not entirely satisfactory. It doesn't play well with activity monitoring (i.e. the red/green can't be seen unless activity monitoring is disabled) and the color change is sticky; it maintains state after you visit the window instead of returning to the default like other tmux monitoring does.

function set_color_from_return_code {
  local bg_color=$([ $? == 0 ] && echo "green" || echo "red")
  tmux set-window-option -t${TMUX_PANE} window-status-bg $bg_color # &> /dev/null
}
PROMPT_COMMAND="set_color_from_return_code"

Edit: Specifically, I'm using tmux as the backend for byobu, so I'm adding the byobu tag, as a byobu-specific solution is fine by me.

1
  1. In your home directory, create a file .exit-monitor.sh, then execute chmod +x .exit-monitor.sh. Write this to it:
#!/bin/bash

if (( $1 == 0 )); then
    tmux set-window-option status-left "#[fg=colour0]#[bg=colour2]$1"
else
    tmux set-window-option status-left "#[fg=colour0]#[bg=colour1]$1"
fi
  1. In your .bashrc, add this:
if echo "$PROMPT_COMMAND" | /bin/grep "exit-monitor" &>/dev/null; then
    export PROMPT_COMMAND=${PROMPT_COMMAND/~\/.exit-monitor.sh \$?;/}
fi

if ps -aux | grep tmux | grep -v grep &>/dev/null; then
    export PROMPT_COMMAND="~/.exit-monitor.sh \$?; $PROMPT_COMMAND"
fi

This will remove the script from PROMPT_COMMAND if it's already in there and re-add it to the beginning of the variable, but only if tmux is running. Otherwise you would keep adding the script to PROMPT_COMMAND over and over again, and you'd get annoying error messages if tmux isn't running.

Now, a little square in the left corner of your tmux status bar will show either green or red and the exit status number. If you want, you can also add text, e.g. FAIL/SUCCESS by using

tmux set-window-option status-left "#[fg=colour0]#[bg=colour1]FAIL"

or similar. Of course you can also change the position, e.g. use status-right. One important note is that .exit-monitor.sh needs to be the first entry in PROMPT_COMMAND for this to work and if you have any other tools writing the status text, those tools have to be able to append their status instead of replacing it.

Very interesting idea by the way, I never thought of this, but will definitely keep this in my setup.

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.