Pretend to be a tty in bash for any command [duplicate]

时间秒杀一切 提交于 2019-11-29 05:55:08

问题


This question already has an answer here:

  • How to trick an application into thinking its stdout is a terminal, not a pipe 8 answers

Whenever I use grep, and I pipe it to an other program, the --color option is not respected. I know I could use --color=always, but It also comes up with some other commands that I would like to get the exact output of that command as the output I would get if I was in a tty.

So my question is, is it possible to trick a command into thinking that the command is run inside a tty ?

For example, running

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

I'd like to be able to write something like :

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), but from what I could read in the docs, I'm not sure it can help for my problem


回答1:


There are a number of options, as outlined by several other Stack Overflow answers (see Caarlos's comment). I'll summarize them here though:

  1. Use script + printf, requires no extra dependencies:

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

    Or make a bash function faketty to encapsulate it:

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

    Or in the fish shell:

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

    (credit goes to this answer)

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

  2. Use the unbuffer command (as part of the expect suite of commands), unfortunately this requires a 50mb+ install, but it's the easiest solution:

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

    Or if you use the fish shell:

    function faketty
        unbuffer -p $argv
    end
    faketty ls --color=auto | cat 
    

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

This is a great article on how TTYs work and what Pseudo-TTYs (PTYs) are, it's worth taking a look at if you want to understand how the linux shell works with file descriptors to pass around input, output, and signals. http://www.linusakesson.net/programming/tty/index.php



来源:https://stackoverflow.com/questions/32910661/pretend-to-be-a-tty-in-bash-for-any-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!