假装是 bash 中的任何命令的 tty

Pretend to be a tty in bash for any command

每当我使用 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 seems to have a tool that might do what I want :empty - run processes and applications under pseudo-terminal (PTY),但根据我在文档中看到的内容,我不确定它是否能帮助解决我的问题

有许多选项,如其他几个 Stack Overflow 答案所述(请参阅 Caarlos's )。不过,我会在这里总结一下:

  1. 使用script + printf,不需要额外的依赖:

     0<&- script -qefc "ls --color=auto" /dev/null | cat
    

    或者做一个bash函数faketty封装一下:

     faketty () {
         script -qefc "$(printf "%q " "$@")" /dev/null
     }
     faketty ls --color=auto | cat  
    

    还是在鱼shell:

     function faketty
         script -qefc "(printf "%q " "$argv")" /dev/null
     end
     faketty ls --color=auto | cat 
    

    (归功于此 answer

    http://linux.die.net/man/1/script

  2. 使用unbuffer命令(作为expect命令套件的一部分),不幸的是这需要额外的包安装,但这是最简单的解决方案:

     sudo apt-get install expect-dev   # or brew install expect
     unbuffer -p ls --color=auto | cat  
    

    或者如果你用鱼 shell:

     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