如何使用ANSI转义序列在bash中捕获终端窗口的标题?

6

我正在使用OSX中的bash命令行。我知道ANSI转义序列\033[21t将检索当前终端窗口的标题。例如:

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

我想要做的是通过脚本以编程方式捕获这些信息,但我不知道如何做到。脚本只会捕获原始的 ANSI 转义序列。比如,下面这个小的 Ruby 脚本:

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()并将输出捕获到文件中,但那也不起作用。) 有人知道如何让这个工作吗?

1个回答

7

此处所述,你需要使用一些“不怀好意”的技巧来使它起作用。

这是一个修改后的脚本:

#!/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   

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接