nu_command/platform/
is_terminal.rs1use nu_engine::command_prelude::*;
9use std::io::IsTerminal as _;
10
11#[derive(Clone)]
12pub struct IsTerminal;
13
14impl Command for IsTerminal {
15 fn name(&self) -> &str {
16 "is-terminal"
17 }
18
19 fn signature(&self) -> Signature {
20 Signature::build("is-terminal")
21 .input_output_type(Type::Nothing, Type::Bool)
22 .switch("stdin", "Check if stdin is a terminal.", Some('i'))
23 .switch("stdout", "Check if stdout is a terminal.", Some('o'))
24 .switch("stderr", "Check if stderr is a terminal.", Some('e'))
25 .category(Category::Platform)
26 }
27
28 fn description(&self) -> &str {
29 "Check if the process stdin, stdout, or stderr is attached to a terminal device."
30 }
31
32 fn extra_description(&self) -> &str {
33 "This is an operating-system level check (like bash `test -t`), not a Nushell
35pipeline check. It reports if the process file descriptor is a TTY, which is
36what scripts need for `./script.nu | cat` vs running on a terminal.
37
38To detect if a custom command's return value is piped or collected inside
39Nushell (pretty output vs structured data), use `is-redirected` instead."
40 }
41
42 fn examples(&self) -> Vec<Example<'_>> {
43 vec![
44 Example {
45 description: "Check if stdout is a terminal (default when no flag is specified).",
46 example: "is-terminal",
47 result: None,
48 },
49 Example {
50 description: r#"Return "terminal attached" if standard input is attached to a terminal, and "no terminal" if not."#,
51 example: r#"if (is-terminal --stdin) { "terminal attached" } else { "no terminal" }"#,
52 result: Some(Value::test_string("terminal attached")),
53 },
54 Example {
55 description: "Choose formatting based on process stdout being a TTY (works inside `if`).",
56 example: r#"if (is-terminal --stdout) { "human" } else { "piped" }"#,
57 result: None,
58 },
59 ]
60 }
61
62 fn search_terms(&self) -> Vec<&str> {
63 vec![
64 "input", "output", "stdin", "stdout", "stderr", "tty", "isatty",
65 ]
66 }
67
68 fn run(
69 &self,
70 engine_state: &EngineState,
71 stack: &mut Stack,
72 call: &Call,
73 _input: PipelineData,
74 ) -> Result<PipelineData, ShellError> {
75 let stdin = call.has_flag(engine_state, stack, "stdin")?;
76 let stdout = call.has_flag(engine_state, stack, "stdout")?;
77 let stderr = call.has_flag(engine_state, stack, "stderr")?;
78
79 let is_terminal = match (stdin, stdout, stderr) {
81 (true, false, false) => std::io::stdin().is_terminal(),
82 (false, false, true) => std::io::stderr().is_terminal(),
83 (false, true, false) | (false, false, false) => std::io::stdout().is_terminal(),
84 _ => {
85 return Err(ShellError::IncompatibleParametersSingle {
86 msg: "Only one stream may be checked".into(),
87 span: call.arguments_span(),
88 });
89 }
90 };
91
92 Ok(PipelineData::value(
93 Value::bool(is_terminal, call.head),
94 None,
95 ))
96 }
97}