这个问题在这里已有答案:
每当我使用grep
,并将其管道到其他程序时,--color
选项不受尊重。我知道我可以使用--color=always
,但是它还提供了一些其他命令,我想得到该命令的确切输出,如果我在tty中我将得到的输出。
所以我的问题是,是否有可能欺骗命令认为命令是在tty内运行的?
例如,跑步
grep --color word file # Outputs some colors
grep --color word file | cat # Doesn't output any colors
我希望能够写出类似的东西:
IS_TTY=TRUE grep --color word file | cat # Outputs some colors
This question似乎有一个工具,可以做我想要的:empty - run processes and applications under pseudo-terminal (PTY),但从我在文档中读到的,我不确定它可以帮助我的问题
有许多选项,正如其他几个Stack Overflow答案所述(参见Caarlos的comment)。我会在这里总结一下:
script
+ printf
,不需要额外的依赖项:
0<&- script -qefc "ls --color=auto" /dev/null | cat
或者使用bash函数faketty
来封装它:
faketty () {
script -qfce "$(printf "%q " "$@")"
}
faketty ls --color=auto | cat
或者在鱼壳中:
function faketty
script -qefc "(printf "%q " "$argv")"
end
faketty ls --color=auto | cat
(功劳归于此answer)
http://linux.die.net/man/1/scriptunbuffer
命令(作为expect
命令套件的一部分),遗憾的是这需要50mb +安装,但这是最简单的解决方案:
sudo apt-get install expect-dev
unbuffer -p ls --color=auto | cat
或者如果你使用鱼壳:
function faketty
unbuffer -p $argv
end
faketty ls --color=auto | cat
http://linux.die.net/man/1/unbuffer这是一篇关于TTY如何工作以及伪TTY(PTY)是什么的伟大文章,如果你想了解linux shell如何使用文件描述符来传递输入,输出和信号,那么值得一看。 http://www.linusakesson.net/programming/tty/index.php