Shell – How to Trick a Command into Thinking Its Output is Going to a Terminal

pipeptyshellstdoutUtilities

Given a command that changes its behaviour when its output is going to a terminal (e.g. produce coloured output), how can that output be redirected in a pipeline while preserving the changed behaviour? There must be a utility for that, which I am not aware of.

Some commands, like grep --color=always, have option flags to force the behaviour, but the question is how to work around programs that rely solely on testing their output file descriptor.

If it matters, my shell is bash on Linux.

Best Answer

You might get what you need by using unbuffer.

unbufferis a tcl / expect script. Look at the source if you want. Also note the CAVEATS section in man.

Also note that it does not execute aliases such as:

alias ls='ls --color=auto'

unless one add a trick as noted by Stéphane Chazelas:

If you do a alias unbuffer='unbuffer ' (note the trailing space), then aliases will be expanded after unbuffer.

Related Question