Force title on GNU screen

gnu-screenwindow titlezsh

By default, the title of a screen session is the name of the last command entered, which is fine for me, but in some cases I'd like to change it. I know the command CtrlA A, but it only changes the title until the next command, and I'd like it to stay there until I decide otherwise.

EDIT:
Here's the preexec function I found in my .zshrc

if [[ "$TERM" == "screen" ]]; then
   local CMD=${1[(wr)^(*=*|sudo|-*)]}
   echo -n "\ek$CMD\e\\"
fi

Best Answer

Depends how things are set up, but by default, something like this should work.

settitle() {
    printf "\033k$1\033\\"
}

Then run:

settitle NEWTITLE.

See screen title docs and GNU screen faq for more details.

Given Ctrl+A A is only changing it until the next command, it's probably being set by $PS1 (all shells), or $PROMPT_COMMAND/DEBUG trap (bash only) or precmd/preexec (zsh only).

You should look for any place that \e or \033 appears with k or \\ after it, basically like my settitle example above.

UPDATE

You said you had a custom preexec.

Why not change it to this:

if [[ "$TERM" == "screen" ]]; then
   local CMD=${1[(wr)^(*=*|sudo|-*)]}
   echo -n "\ek${TITLE:-$CMD}\e\\"
fi

Then you can set a custom title by running:

TITLE="my title"

and unset the title by running

TITLE=

Don't forget to change precmd and $PS1 as well if necessary.

ASIDE

You could even extend this to all terminals (e.g. xterm, gnome-terminal, etc.) by not hard coding the \ek and \e\\.

This is how I do it:

terminit()
{
    # determine the window title escape sequences
    case "$TERM" in
    aixterm|dtterm|putty|rxvt|xterm*)
        titlestart='\033]0;'
        titlefinish='\007'
        ;;
    cygwin)
        titlestart='\033];'
        titlefinish='\007'
        ;;
    konsole)
        titlestart='\033]30;'
        titlefinish='\007'
        ;;
    screen*)
        # status line
        #titlestart='\033_'
        #titlefinish='\033\'
        # window title
        titlestart='\033k'
        titlefinish='\033\'
        ;;
    *)
        if type tput >/dev/null 2>&1
        then
            if tput longname >/dev/null 2>&1
            then
                titlestart="$(tput tsl)"
                titlefinish="$(tput fsl)"
            fi
        else
            titlestart=''
            titlefinish=''
        fi
        ;;
    esac
}


# or put it inside a case $- in *i* guard
if test -t 0; then
    terminit
fi

# set the xterm/screen/etc. title
settitle()
{
    test -z "${titlestart}" && return 0

    printf "${titlestart}$*${titlefinish}"
}

Then you can change your preexec to:

if [[ "$TERM" == "screen" ]]; then
   local CMD=${1[(wr)^(*=*|sudo|-*)]}
   settitle "${TITLE:-$CMD}"
fi
Related Question