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

折月煮酒 提交于 2019-12-10 15:08:36

问题


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?


回答1:


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   


来源:https://stackoverflow.com/questions/4471278/how-to-capture-the-title-of-a-terminal-window-in-bash-using-ansi-escape-sequence

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!