开发者

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

开发者 https://www.devze.com 2023-01-31 16:04 出处:网络
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:

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 o开发者_如何学JAVAf 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?


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   
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号