welcome/
java-mcmc/
software/
papers/
links/
email me

How to display the current command line in an xterm title with Bash

At the time of writing, the bash(1) shell has a variable PROMPT_COMMAND, whose contents is executed just before each prompt appears. For example, if we type

% PROMPT_COMMAND='echo -ne "\033]0;${PWD}\007"'

then the xterm title will contain the current working directory, and this is updated after each command is executed, just before the new prompt. Unfortunately, this is not suitable for displaying the currently executing shell command, since PROMPT_COMMAND is only called after the current command has finished, which is often too late.

To display the current command line in the xterm title right before it gets executed by bash(1), we can use the shell's programmable completion facilities as follows: At the prompt %, suppose the user has written

% some stuff <RETURN>

we want to change this to

% foo some stuff <TAB>

which, through programmable completion, executes the function fooF(), changing the xterm title along the way. Afterwards, we change the command line back to

% some stuff \n

That's it! To implement the details, simply add the following code to to your .bashrc file.

Note: starting with version 3, bash has several new environment variables which can also be used to display the title of the current command. See BASH_COMMAND, trap and DEBUG. The readline method above works in earlier versions of bash, and of course in later versions.