Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture the title of a terminal window in bash using ANSI escape sequences?

Tags:

terminal

ruby

I am using the bash command line in OSX. I know that the ANSI escape sequence \033[21t will retrieve the title of the current terminal window. So, for example:

$ echo -ne "\033[21t"
...sandbox... 
$ # Where "sandbox" is the title of the current terminal window
$ # and the ... are some extra control characters

What I'd like to do is capture this information programmatically in a script, but I can't figure out how to do it. What the script captures just the raw ANSI escape sequence. So, for further example, this little Ruby script:

cmd = 'echo -ne "\033[21t"'
puts "Output from echo (directly to terminal):"
system(cmd)
terminal_name=`#{cmd}`
puts "\nOutput from echo to variable:"
puts terminal_name.inspect

Produces the following output:

Output from echo (directly to terminal):
^[]lsandbox^[\
Output from echo to variable:
"\e[21t"

I'd like the information in the second case to match the information shown on the terminal, but instead all I get is the raw command sequence. (I've tried using system() and capturing the output to a file -- that doesn't work, either.) Does anyone know a way to get this to work?

like image 772
rleber Avatar asked Dec 17 '10 14:12

rleber


People also ask

Do ANSI escape sequences work on Windows?

The Win32 console does not natively support ANSI escape sequences at all. Software such as Ansicon can however act as a wrapper around the standard Win32 console and add support for ANSI escape sequences. How to load ANSI escape codes or get coloured file listing in WinXP cmd shell?

How do ANSI escape codes work?

The Ansi escape codes let you set the color of the text-background the same way it lets you set the color of the foregrond. For example, the 8 background colors correspond to the codes: Background Black: \u001b[40m. Background Red: \u001b[41m.

What is ANSI in terminal?

ANSI escape sequences are a standard for in-band signaling to control cursor location, color, font styling, and other options on video text terminals and terminal emulators. Certain sequences of bytes, most starting with an ASCII escape character and a bracket character, are embedded into text.

What is ESC M?

ESC M. moves cursor one line up, scrolling if needed. ESC 7. save cursor position (DEC)


1 Answers

As detailed here you have to use dirty tricks to get that to work.

Here is a modified script:

#!/bin/bash
# based on a script from http://invisible-island.net/xterm/xterm.faq.html
exec < /dev/tty
oldstty=$(stty -g)
stty raw -echo min 0
# on my system, the following line can be replaced by the line below it
echo -en "\033[21t" > /dev/tty
read -r x
stty $oldstty
echo $x   
like image 178
prater Avatar answered Sep 20 '22 09:09

prater