Change the current terminal tab title inside a shell script

The script works by setting the shell's interactive prompt to a string which includes control codes to manipulate the xterm window title. Each time the shell's prompt is displayed, the control codes to change the window title are output.

But of course, inside a script, no interactive prompt is ever displayed, so these commands have no observable effect (though if you started another interactive shell from within the script, you could see the window title change). And because no script can change the environment of its parent process, the change is lost once your script terminates.

Anyway, from your script, you could of course print out the control codes directly.

printf '\033]2;Hello\a'

This changes the window's title once, but if any other program later changes it again, your old title will be lost. The trick to change your prompt is widespread because some popular programs in the past would often change your window title soon after you changed it to your liking (though I don't think this is a common problem any longer). The drawback is that if something has a genuine reason to change your window title, that will now be superseded as soon as your shell displays its prompt again.

If you want code to change your current shell's prompt, you can't put those in a regular script; but you can source the script file, or put the commands in a shell function instead (commonly done in your Bash profile in order to make it persistent).

Incidentally, the Bash prompt should include additional control codes to tell Bash when a part of the prompt is effectively zero width, as far as calculating the display width of the prompt is concerned. You will find that line wrapping is erratic if you type a long command and then need to backspace, for example; Bash will attempt to redraw the prompt, but does it in the wrong place, because it thinks the screen control codes contribute to the prompt's width. You'll want to add these \[ and \] Bash control codes around them.

PS1="$ORIG\[$TITLE\]"

(The curly braces aren't really contributing anything, and hamper legibility, so I took them out.)

Tags:

Shell

Terminal