A terminal is a display unit that is part of the user interface to a computer system. The word carries the connotation of being text-only.
Terminal emulators for Linux have support for ANSI escape codes built in.
chan configure can be used to determine whether a channel is connected to a terminal:
proc isatty chan { expr {[catch {chan configure $chan -mode}] == 0} }
Credit to [L1 ] for the idea.
However, this doesn't work on Windows.
AMG: To check if stdin is connected to a terminal, run:
if {![catch {exec /usr/bin/tty -s}]} { # stdin is a terminal }
Checking for stdout/stderr is harder because exec does not allow stdout/stderr to be redirected to stdin because stdout/stderr are not considered readable. Instead, let the shell do the redirection. Furthermore, instruct [exec] to not intercept stdout/stderr.
if {![catch {exec /bin/sh -c {/usr/bin/tty -s < /dev/stdout} >@ stdout}]} { # stdout is a terminal } if {![catch {exec /bin/sh -c {/usr/bin/tty -s < /dev/stderr} 2>@ stderr}]} { # stderr is a terminal }
Without the -s switch, the tty program not only checks if its stdin is a terminal, but it also prints the device name to its stdout, e.g. /dev/pts/0.
MHo 2021-09-17: How to test this on Windows? I found the following way if twapi is available:
package require twapi twapi::import_commands proc isStdinRedirected {} { catch {get_tcl_channel_handle stdin write} } puts [isStdinRedirected]
Examples:
c:\Users\matthiasu\usr\pgm\tcl\usr\Tst\isatty>echo test|tclkitsh test8.tcl 1 c:\Users\matthiasu\usr\pgm\tcl\usr\Tst\isatty>tclkitsh test8.tcl<nul 1 c:\Users\matthiasu\usr\pgm\tcl\usr\Tst\isatty>tclkitsh test8.tcl 0
Tcl internally uses isatty(). Perhaps it could provide the following command:
chan isatty ...