I'd like to disable colors when the output is piped somewhere else than a terminal.
Asked
Active
Viewed 2,140 times
7
-
9To rephrase this: you want to check whether `stdout` is a TTY. You might want to check the `isatty` function or a crate wrapping it for compatibility, eg. https://crates.io/crates/atty. – SirDarius Jan 02 '19 at 22:15
2 Answers
12
Translated into the POSIX language, your question would be: "is stdout not a TTY", so the answer on *nix can be obtained by !isatty(STDOUT_FILENO)
. The libc crate can be used to call this from Rust.
On Windows, it's complicated, so you're better off using the atty crate.
[edit] You can use the atty
crate on Linux as well, making it a convenient solution for cross-platform programs.

Nickolay
- 31,095
- 13
- 107
- 185
-
Is there any reason to go via `libc`? The atty crate is cross-platform. – Peter Hall Jan 29 '19 at 13:19
-
The only reason I can think of is avoiding an extra dependency, while not needing to be cross-platform. – Nickolay Jan 29 '19 at 13:34
-
3
As of Rust 1.70, this is in std:
use std::io::IsTerminal;
fn main() {
dbg!(std::io::stdout().is_terminal());
}
Alternatively, crossterm has a is_tty() method, and there's also the is-terminal crate (a maintained fork of atty
).

Wilfred Hughes
- 29,846
- 15
- 139
- 192