I found a C program which can do it with the Xterm control codes and without X11, it works for me:
xtermcontrol --get-title | read A ; echo "$A"
http://www.thrysoee.dk/xtermcontrol/
It should be easy enough to extract / replicate the get_title() function into your own code, or to do it in a different language.
There was a security issue with reading the title, if people cat files such a file could set the title to 'rm -rf /' then 'get' it again which would send that command to your terminal. So sometimes it's disabled by default. The allowWindowOps resource can be used to enable it again.
http://invisible-island.net/xterm/xt...tml#window_ops
I think this security issue has been resolved by escaping the title somehow so it cannot be interpreted as a command. The demo exploit attached here does not work on my system, anyway:
http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=384593
Getting the title is also described here, but the demo perl code did not work for me:
http://www.perlmonks.org/?node_id=792957
Vim (the version I'm using) relies on X11 to restore the title. If DISPLAY is unset and 'title' is set, vim sets the title to 'Thanks for flying vim!' on exit.
Since I only set terminal titles actively myself, using my own script, the best solution for me might be to store the title in an environment variable $TERM_TITLE, when setting it. Then I can save the old title as needed and restore it later. This workaround would not be much use if you are writing an app which is supposed to work in any environment.