From: Phil Sutter Subject: [iproute PATCH v2 4/4] lib: Enable colored output only for TTYs Date: Wed, 15 Aug 2018 18:21:27 +0200 Message-ID: <20180815162127.21477-5-phil@nwl.cc> References: <20180815162127.21477-1-phil@nwl.cc> Cc: netdev@vger.kernel.org, Till Maas , David Ahern To: Stephen Hemminger Return-path: Received: from orbyte.nwl.cc ([151.80.46.58]:41122 "EHLO orbyte.nwl.cc" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1729300AbeHOTOh (ORCPT ); Wed, 15 Aug 2018 15:14:37 -0400 In-Reply-To: <20180815162127.21477-1-phil@nwl.cc> Sender: netdev-owner@vger.kernel.org List-ID: Add an additional prerequisite to check_enable_color() to make sure stdout actually points to an open TTY device. Otherwise calls like | ip -color a s >/tmp/foo will print color escape sequences into that file. Allow to override this check by specifying '-color' flag more than once. Signed-off-by: Phil Sutter --- Changes since v1: - Allow to override isatty() check by specifying '-color' flag more than once. - Document new behaviour in man pages. --- lib/color.c | 6 +++++- man/man8/bridge.8 | 5 ++++- man/man8/ip.8 | 5 ++++- man/man8/tc.8 | 5 ++++- 4 files changed, 17 insertions(+), 4 deletions(-) diff --git a/lib/color.c b/lib/color.c index edf96e5c6ecd7..3a66d8ccb4b00 100644 --- a/lib/color.c +++ b/lib/color.c @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -79,7 +80,10 @@ void enable_color(void) int check_enable_color(int color, int json) { - if (color && !json) { + if (json || !color) + return 1; + + if (color > 1 || isatty(fileno(stdout))) { enable_color(); return 0; } diff --git a/man/man8/bridge.8 b/man/man8/bridge.8 index e7f7148315e19..b865e8b6cd771 100644 --- a/man/man8/bridge.8 +++ b/man/man8/bridge.8 @@ -171,7 +171,10 @@ return code will be non zero. .TP .BR "\-c" , " -color" -Use color output. +Use color output if stdout is a terminal. Specify twice to enable color output +irrespective of stdout state. This flag is ignored if +.B \-json +is also given. .TP .BR "\-j", " \-json" diff --git a/man/man8/ip.8 b/man/man8/ip.8 index 0087d18b74706..c5484bbc11483 100644 --- a/man/man8/ip.8 +++ b/man/man8/ip.8 @@ -188,7 +188,10 @@ executes specified command over all objects, it depends if command supports this .TP .BR "\-c" , " -color" -Use color output. +Use color output if stdout is a terminal. Specify twice to enable color output +irrespective of stdout state. This flag is ignored if +.B \-json +is also given. .TP .BR "\-t" , " \-timestamp" diff --git a/man/man8/tc.8 b/man/man8/tc.8 index 840880fbdba63..cbe7ac1847bbb 100644 --- a/man/man8/tc.8 +++ b/man/man8/tc.8 @@ -730,7 +730,10 @@ option. .TP .BR "\ -color" -Use color output. +Use color output if stdout is a terminal. Specify twice to enable color output +irrespective of stdout state. This flag is ignored if +.B \-json +is also given. .TP .BR "\-j", " \-json" -- 2.18.0