如何使用 ANSI 转义序列在 bash 中捕获终端窗口的标题? [英] How to capture the title of a terminal window in bash using ANSI escape sequences?
问题描述
我在 OSX 中使用 bash 命令行.我知道 ANSI 转义序列 \033[21t 将检索当前终端窗口的标题.因此,例如:
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
我想做的是在脚本中以编程方式捕获此信息,但我不知道该怎么做.脚本仅捕获原始 ANSI 转义序列的内容.所以,再举个例子,这个小 Ruby 脚本:
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
产生以下输出:
Output from echo (directly to terminal):
^[]lsandbox^[\
Output from echo to variable:
"\e[21t"
我希望第二种情况下的信息与终端上显示的信息相匹配,但我得到的只是原始命令序列.(我已经尝试使用 system() 并将输出捕获到文件中——这也不起作用.)有没有人知道让这个工作的方法?
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.
这是修改后的脚本:
#!/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
这篇关于如何使用 ANSI 转义序列在 bash 中捕获终端窗口的标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!