Set xterm (PuTTY) window title when using screen

gnu-screenputty

I am trying to get screen to set my xterm title. I have this working outside of screen, but screen keeps whatever title was in place when I started it. Here is my .bashrc:

function bash_prompt_command() {
    # How many characters of the $PWD should be kept
    local pwdmaxlen=25
    # Indicate that there has been dir truncation
    local trunc_symbol=".."
    local dir=${PWD##*/}
    pwdmaxlen=$(( ( pwdmaxlen < ${#dir} ) ? ${#dir} : pwdmaxlen ))
    NEW_PWD=${PWD/#$HOME/\~}
    local pwdoffset=$(( ${#NEW_PWD} - pwdmaxlen ))
    if [ ${pwdoffset} -gt "0" ]
    then
        NEW_PWD=${NEW_PWD:$pwdoffset:$pwdmaxlen}
        NEW_PWD=${trunc_symbol}/${NEW_PWD#*/}
    fi

    export NEW_PWD
}

PROMPT_COMMAND=bash_prompt_command
# Color chart @ http://wiki.archlinux.org/index.php/Color_Bash_Prompt
case "${TERM}" in
    "xterm")
        TITLEBAR='\[\033]0;\u@\h > ${NEW_PWD}\007\]'
        PS1="${TITLEBAR}\[\e[1;32m\][\e[0;36m\]\u\e[1;32m\]@\e[1;33m\]\h\e[1;32m\]] \e[0;37m\]\${NEW_PWD}/ \e[1;32m\]\$ \[\e[0m"
        ;;
    "screen")
        TITLEBAR='\[\033]0;\u@\h > ${NEW_PWD}\007\]'
        ESC='\[\ek\e\\\]'
        PS1="${TITLEBAR}\[\e[1;32m\][\e[0;36m\]\u\e[1;32m\]] \e[0;37m\]\${NEW_PWD}/ \e[1;32m\]\$ ${ESC}\[\e[0m"
        ;;
    *)
        PS1="\[\e[1;32m\][\e[0;36m\]\u\e[1;32m\]@\e[1;33m\]\h\e[1;32m\]] \e[0;37m\]\${NEW_PWD}/ \e[1;32m\]\$ \[\e[0m"
    ;;
esac

And here is my .screenrc:

hardstatus alwayslastline
hardstatus string '%{= kg}[%{Y}%H%{g}][%= %{= kw}%?%-Lw%?%{=b kR}(%{W}%n-%t%?(%u)%?%{=b kR})%{= kw}%?%+Lw%?%?%= %{g}][%{Y}%l%{g}]%{g}[%{B}%m.%d.%Y %{G}%c%{g}]'

termcapinfo xterm|xterms|xs|rxvt ti@:te@
termcapinfo xterm 'hs:ts=\E]2;:fs=\007:ds=\E]2;screen\007'

altscreen on
shelltitle '$ |bash'

What am I doing incorrectly?

Update (19 August 2010):
The problem is that you cannot update the terminal's title from within screen when you set alwayslastline. So my solution was to just give up and settle for a predetermined, useful, title for my screen sessions. My updated .bashrc and .screenrc can be found at http://bitbucket.org/jsumners/rcfiles/src.

Best Answer

The escape codes are different inside screen.

This outside of screen:

PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME}: ${PWD}\007"'

is equivalent to this inside screen:

PROMPT_COMMAND='echo -ne "\033_${USER}@${HOSTNAME}: ${PWD}\033\\"'

Changing your case ${TERM}="screen" titlebar to

TITLEBAR='\[\033_\u@\h > ${NEW_PWD}\033\\\]'

will solve your problem.