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

前端之家收集整理的这篇文章主要介绍了假装在任何命令的bash中都是tty前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Trick an application into thinking its stdout is a terminal,not a pipe8个
每当我使用grep,并将其传递给其他程序时,都不会遵守–color选项.我知道我可以使用–color = always,但它还提供了一些其他命令,我想获得该命令的确切输出,如果我在tty中,我将得到的输出.

所以我的问题是,是否有可能欺骗命令认为命令是在tty内运行的?

例如,跑步

  1. grep --color word file # Outputs some colors
  2. grep --color word file | cat # Doesn't output any colors

我希望能够写出如下内容

  1. IS_TTY=TRUE grep --color word file | cat # Outputs some colors

This question似乎有一个可能做我想要的工具:empty – run processes and applications under pseudo-terminal (PTY),但从我在文档中可以阅读的内容,我不确定它可以帮我解决我的问题

有许多选项,如其他几个Stack Overflow答案所述(参见 Caarloscomment).我会在这里总结一下:

>使用脚本printf,不需要额外的依赖项:

  1. 0<&- script -qfce "ls --color=auto" /dev/null | cat

或者使用bash函数faketty来封装它:

  1. faketty () {
  2. script -qfce "$(printf "%q " "$@")"
  3. }
  4. faketty ls --color=auto | cat

或者在鱼壳里:

  1. function faketty
  2. script -qfce "(printf "%q " "$argv")"
  3. end
  4. faketty ls --color=auto | cat

(信用到这个answer)

http://linux.die.net/man/1/script
>使用unbuffer命令(作为期望的命令套件的一部分),遗憾的是这需要50mb安装,但这是最简单的解决方案:

  1. sudo apt-get install expect-dev
  2. unbuffer -p ls --color=auto | cat

或者如果你使用鱼壳:

  1. function faketty
  2. unbuffer -p $argv
  3. end
  4. 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

猜你在找的Bash相关文章