# Setting Screen's title to the currently running process with bash

This is the first of a series of at least two posts about how I’ve configured the excellent Gnu Screen to fit my needs and make me more productive.

My workflow tends to be fairly disjointed, simply because I tend to do a mix of system administration and programming, with user requests scattered through the day. I decided to start using screen at work because I was having a number of connection dropouts, and having to start from scratch quite often. It’s important for me to have a visual cue of what’s going on in each virtual terminal, as I’ll often have 6 or 7 or more tasks going at once. Given that I’m not bloody likely to manually change the title each time I start a task, I needed a way to automatically do so. This page from the excellent screen faq on aperiodic.net has instructions that tell you how to use a clever combination of the shelltitle screen configuration and a bash prompt setting to let you set the title to the current running process. However, this just gives the process name, and not arguments - so, I would have three shells titled ‘vi’, and another four titled ‘ssh’. Not so much use, not knowing what I’m editing, or what hosts I’m logged onto. Unfortunately, bash doesn’t have a preexec() built-in like zsh does. I suppose that I could switch to zsh, but I’m ornery.

However, I did find an excellent post on davidpashley.com that gave me the key. An extremely clever use of a trap will let you emulate zsh’s preexec function and run whatever you like just before each command is executed. Here’s how I modified his code:

case "$TERM" in screen) set -o functrace trap 'echo -ne "\ek\$:${BASH_COMMAND:0:20}\e\\"' DEBUG export PS1='$\033k:\W\033\\$\u@\h:\w\$ '
;;
*)
;;
esac


Finally, here’s the obligatory screenshot.

I’m glad i found this page. I was desperately trying to do something like this. I have a few questions: echo -ne “\ek\${1%% *}\e\” <- I know what that does, but what is it for ? echo -n ‘’ <- why echoing and empty string ?

Also i see you mixed \e and \033 depending on the context (both ESC command) and you’re a 100% right because using \e in PS1 doesn’t work as expected. Do you know why ?

sorry I didn’t notice this comment until now, need to set up email notifications!

questions 1 and 2 - good question! Neither are necessary, and must have been a result of the different things I tried while I was getting this to work… I’ll modify the code sample, thanks!

question 3 - the reason (I think) that \e doesn’t work in PS1 is because it is an escape only understood by bash’s ‘echo’ built-in, and not interpreted in prompts. (see the section on echo in the bash man page)

Is it possible to view the host name and command while you are logged into a different server? For example, when I run screen on server A, then ssh into server B, the screen title stays as ssh server B.

Post Comment