On Windows, connecting to tmux 1.8 on CentOS 7 through MobaXterm.

Ideally, I want my tmux windows to have the name of the last command that I typed in whichever pane is active (like, cd /home not bash like {pane_current_command} prints). I have no idea how to do that, so instead I'm trying to find out how to get the name match the PS1 of the active pane. I tried the suggestions in this answer with this in my bashrc:

settitle() {
    printf "\033k$1\033\\"
PROMPT_COMMAND='if [ $? -eq 0 ]; then ((counter++)); else counter=0; fi; settitle($basic_prompt)'
PS1='(\[\e[4m\]${USER:0:3}\[\e[0m\]@\[\e[34m\]${PWD:${#PWD}<15?0:(-15)}\[\e[m\])[$counter]\\$ '

and got

bash: PROMPT_COMMAND: line 10: syntax error near unexpected token '$basic_prompt'

  1. Is there any way to name a tmux window by the last completed command?

  2. If not, how can I correctly get it to set to my PS1, which is dynamic based on my username and path?


Solved for tmux 2.6 and tmux 1.8 (tested on both).

To have tmux display a dynamic window title, edit your ~/.bashrc to something similar to the following:

settitle() {
    printf "\033k$1\033\\"
PROMPT_COMMAND='if [ "$TERM" =~ "screen" ]; then eval prompt=$dynamic_window_title; settitle "$prompt"; fi;'

And you'll (probably) need you ~/.tmux.conf to have:

setw -g automatic-rename on

As I understand it, settitle() is basically renaming your window after every command you execute. I don't fully understand how it does this.

PROMPT_COMMAND is part of bash that is run after every command you run, which allows you to do cool things like keeping track of how many correct bash commands you've typed in a row, in addition to our use here of continually redefining our title.

$TERM is an environment variable which for me is either set to "screen" (or something like "screen-256color") when in tmux or to "xterm" when using MobaXterm. We check for this because otherwise your $PS1 is essentially double-printed when not in tmux.

The dynamic_title must be in single quotes, otherwise it will be defined when you source your ~/.bashrc and not be dynamic. However, you need it to be defined at some point or else your window will be renamed literally ${USER:0:3}@${PWD:${#PWD}<15?0:(-15)}. This is what eval does, creating a string that is literally what you want the window title to be. Then we just give that string to settitle(), wrapped in double quotes so spaces work correctly.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.