Check input device is a terminal: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(17 intermediate revisions by 11 users not shown)
Line 1: Line 1:
[[Category:Terminal control]]
{{draft task}}
[[Category:Hardware]]
[[Category:Initialization]]
{{task}}


;Task:
;Task:
Line 8: Line 11:
*   [[Check output device is a terminal]]
*   [[Check output device is a terminal]]
<br><br>
<br><br>

=={{header|Ada}}==
=={{header|Ada}}==
{{works with|GNAT}}
{{works with|GNAT}}
We use the interface to C library functions <code>isatty()</code> and <code>fileno()</code>.
We use the interface to C library functions <code>isatty()</code> and <code>fileno()</code>.


<lang ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Interfaces.C_Streams; use Interfaces.C_Streams;
with Interfaces.C_Streams; use Interfaces.C_Streams;


Line 23: Line 25:
Put_Line(Standard_Error, "stdin is a tty.");
Put_Line(Standard_Error, "stdin is a tty.");
end if;
end if;
end Test_tty;</lang>
end Test_tty;</syntaxhighlight>


{{out}}
{{out}}
Line 34: Line 36:
</pre>
</pre>


=={{header|BaCon}}==
=={{header|BASIC}}==
==={{header|BaCon}}===
<lang freebasic>terminal = isatty(0)
<syntaxhighlight lang="freebasic">terminal = isatty(0)
PRINT terminal</lang>
PRINT terminal</syntaxhighlight>


{{out}}
{{out}}
Line 48: Line 51:
prompt$ ./istty <<<"testing"
prompt$ ./istty <<<"testing"
0</pre>
0</pre>

==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">
Open Cons For Input As #1
' Open Cons abre los flujos de entrada (stdin) o salida (stdout) estándar
' de la consola para leer o escribir.

If Err Then
Print "Input doesn't come from tt."
Else
Print "Input comes from tty."
End If
Close #1
Sleep
</syntaxhighlight>



=={{header|C}}==
=={{header|C}}==
Use <code>isatty()</code> on file descriptor to determine if it's a TTY. To get the file descriptor from a <code>FILE*</code> pointer, use <code>fileno</code>:
Use <code>isatty()</code> on file descriptor to determine if it's a TTY. To get the file descriptor from a <code>FILE*</code> pointer, use <code>fileno</code>:
<lang c>#include <unistd.h> //for isatty()
<syntaxhighlight lang="c">#include <unistd.h> //for isatty()
#include <stdio.h> //for fileno()
#include <stdio.h> //for fileno()


Line 60: Line 79:
: "stdin is not tty");
: "stdin is not tty");
return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 70: Line 89:
stdin is not tty
stdin is not tty
</pre>
</pre>

=={{header|COBOL}}==
=={{header|COBOL}}==
Works with GnuCOBOL.
Works with GnuCOBOL.


<lang cobol> *>
<syntaxhighlight lang="cobol"> *>
*> istty, check id fd 0 is a tty
*> istty, check id fd 0 is a tty
*> Tectonics: cobc -xj istty.cob
*> Tectonics: cobc -xj istty.cob
Line 99: Line 117:


goback.
goback.
end program istty.</lang>
end program istty.</syntaxhighlight>


DISPLAY for fd 1 is directed to SYSERR to get some output during the various trials.
DISPLAY for fd 1 is directed to SYSERR to get some output during the various trials.
Line 121: Line 139:
fd 0 tty: +0000000000
fd 0 tty: +0000000000
fd 2 tty: +0000000000</pre>
fd 2 tty: +0000000000</pre>

=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
{{Works with|SBCL}}
{{Works with|SBCL}}
<lang lisp>(with-open-stream (s *standard-input*)
<syntaxhighlight lang="lisp">(with-open-stream (s *standard-input*)
(format T "stdin is~:[ not~;~] a terminal~%"
(format T "stdin is~:[ not~;~] a terminal~%"
(interactive-stream-p s)))</lang>
(interactive-stream-p s)))</syntaxhighlight>


{{Out}}
{{Out}}
Line 135: Line 152:
$ echo "" | sbcl --script rc.lisp
$ echo "" | sbcl --script rc.lisp
stdin is not a terminal</pre>
stdin is not a terminal</pre>

=={{header|Crystal}}==
=={{header|Crystal}}==
<lang ruby>File.new("testfile").tty? #=> false
<syntaxhighlight lang="ruby">File.new("testfile").tty? #=> false
File.new("/dev/tty").tty? #=> true
File.new("/dev/tty").tty? #=> true
STDIN.tty? #=> true</lang>
STDIN.tty? #=> true</syntaxhighlight>

=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio;
<syntaxhighlight lang="d">import std.stdio;


extern(C) int isatty(int);
extern(C) int isatty(int);
Line 151: Line 166:
else
else
writeln("Input doesn't come from tty.");
writeln("Input doesn't come from tty.");
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>C:\test
<pre>C:\test
Line 157: Line 172:
C:\test < in.txt
C:\test < in.txt
Input doesn't come from tty.</pre>
Input doesn't come from tty.</pre>


=={{header|Forth}}==
{{works with|gforth|0.7.3}}
In Gforth, the word "source-id" is used to determine the program source.

If you got a program file "source.f":
<syntaxhighlight lang="Forth">
: ?tty source-id if ." not " then ." from terminal" ; ?tty bye
</syntaxhighlight>
Then,
<syntaxhighlight lang="bash">gforth source.f</syntaxhighlight> in the shell will display:
{{out}}<pre>not from terminal</pre>
Then,
<syntaxhighlight lang="bash">gforth -e ': ?tty source-id if ." not " then ." from terminal" ; ?tty bye'</syntaxhighlight> will display:
{{out}}<pre>not from terminal</pre>

At Gforth prompt,
<syntaxhighlight lang="bash">: ?tty source-id if ." not " then ." from terminal" ; ?tty bye</syntaxhighlight> will display:
{{out}}<pre>from terminal</pre>


=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"

BeginCCode
if (isatty(fileno(stdin)))
NSLog( @"stdin is connected to a terminal" );
else
NSLog( @"stdin is NOT connected to a terminal" );
EndC

HandleEvents
</syntaxhighlight>
{{output}}
<pre>
stdin is NOT connected to a terminal
</pre>



=={{header|Go}}==
=={{header|Go}}==
{{libheader|Go sub-repositories}}
{{libheader|Go sub-repositories}}
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 174: Line 229:
fmt.Println("Who are you? You're not a terminal.")
fmt.Println("Who are you? You're not a terminal.")
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 182: Line 237:
Who are you? You're not a terminal.
Who are you? You're not a terminal.
</pre>
</pre>



=={{header|Haskell}}==
=={{header|Haskell}}==
Line 187: Line 243:
Example uses [https://hackage.haskell.org/package/unix <tt>unix</tt>] package:
Example uses [https://hackage.haskell.org/package/unix <tt>unix</tt>] package:


<lang haskell>module Main (main) where
<syntaxhighlight lang="haskell">module Main (main) where
import System.Posix.IO (stdInput)
import System.Posix.IO (stdInput)
Line 197: Line 253:
putStrLn $ if isTTY
putStrLn $ if isTTY
then "stdin is TTY"
then "stdin is TTY"
else "stdin is not TTY"</lang>
else "stdin is not TTY"</syntaxhighlight>

=={{header|Jsish}}==
=={{header|Jsish}}==
<lang javascript>/* Check input device is a terminal, in Jsish */
<syntaxhighlight lang="javascript">/* Check input device is a terminal, in Jsish */
;Interp.conf().subOpts.istty;
;Interp.conf().subOpts.istty;


Line 207: Line 262:
Interp.conf().subOpts.istty ==> false
Interp.conf().subOpts.istty ==> false
=!EXPECTEND!=
=!EXPECTEND!=
*/</lang>
*/</syntaxhighlight>


{{out}}
{{out}}
Line 217: Line 272:
prompt$ jsish --U checkInputDevice.jsi
prompt$ jsish --U checkInputDevice.jsi
Interp.conf().subOpts.istty ==> false</pre>
Interp.conf().subOpts.istty ==> false</pre>

=={{header|Julia}}==
=={{header|Julia}}==
<syntaxhighlight lang="julia">
<lang Julia>
if isa(STDIN, Base.TTY)
if isa(STDIN, Base.TTY)
println("This program sees STDIN as a TTY.")
println("This program sees STDIN as a TTY.")
Line 225: Line 279:
println("This program does not see STDIN as a TTY.")
println("This program does not see STDIN as a TTY.")
end
end
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 231: Line 285:
This program sees STDIN as a TTY.
This program sees STDIN as a TTY.
</pre>
</pre>

=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{Works with|Ubuntu|14.04}}
{{Works with|Ubuntu|14.04}}
<lang scala>// Kotlin Native version 0.5
<syntaxhighlight lang="scala">// Kotlin Native version 0.5


import platform.posix.*
import platform.posix.*
Line 244: Line 297:
println("stdin is not a terminal")
println("stdin is not a terminal")
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 250: Line 303:
stdin is a terminal
stdin is a terminal
</pre>
</pre>

=={{header|Nemerle}}==
=={{header|Nemerle}}==
There is no explicit way (ie <tt>isatty()</tt>)to do this; however, if we ''assume'' that standard input ''is'' a terminal, we can check if the input stream has been redirected (presumably to something other than a terminal).
There is no explicit way (ie <tt>isatty()</tt>)to do this; however, if we ''assume'' that standard input ''is'' a terminal, we can check if the input stream has been redirected (presumably to something other than a terminal).
<lang Nemerle>def isTerm = System.Console.IsInputRedirected;</lang>
<syntaxhighlight lang="nemerle">def isTerm = System.Console.IsInputRedirected;</syntaxhighlight>
=={{header|Nim}}==
Using function "isatty" of standard module "terminal" which accepts a File as argument.


<syntaxhighlight lang="nim">import terminal

echo if stdin.isatty: "stdin is a terminal" else: "stdin is not a terminal"</syntaxhighlight>

{{out}}
<pre>Command: ./check_input_dev
Result: stdin is a terminal</pre>

<pre>Command: ./check_input_dev <somefile
Result: stdin is not a terminal</pre>
=={{header|OCaml}}==
=={{header|OCaml}}==


<lang ocaml>let () =
<syntaxhighlight lang="ocaml">let () =
print_endline (
print_endline (
if Unix.isatty Unix.stdin
if Unix.isatty Unix.stdin
then "Input comes from tty."
then "Input comes from tty."
else "Input doesn't come from tty."
else "Input doesn't come from tty."
)</lang>
)</syntaxhighlight>


Testing in interpreted mode:
Testing in interpreted mode:
Line 271: Line 335:
Input doesn't come from tty.
Input doesn't come from tty.
</pre>
</pre>
=={{header|Ol}}==

<syntaxhighlight lang="scheme">
(define (isatty? fd) (syscall 16 fd 19))
(print (if (isatty? stdin)
"Input comes from tty."
"Input doesn't come from tty."))
</syntaxhighlight>
=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>use strict;
<syntaxhighlight lang="perl">use strict;
use warnings;
use warnings;
use 5.010;
use 5.010;
Line 281: Line 351:
else {
else {
say "Input doesn't come from tty.";
say "Input doesn't come from tty.";
}</lang>
}</syntaxhighlight>


$ perl istty.pl
$ perl istty.pl
Line 287: Line 357:
$ true | perl istty.pl
$ true | perl istty.pl
Input doesn't come from tty.
Input doesn't come from tty.

=={{header|Phix}}==
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(notonline)-->
Requires 0.8.2+
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (no input redirection in a browser!)</span>
<lang Phix>printf(1,"stdin:%t, stdout:%t, stderr:%t\n",{isatty(0),isatty(1),isatty(2)})</lang>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"stdin:%t, stdout:%t, stderr:%t\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">isatty</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">),</span><span style="color: #000000;">isatty</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">),</span><span style="color: #000000;">isatty</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)})</span>
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 298: Line 369:
stdin:false, stdout:true, stderr:true
stdin:false, stdout:true, stderr:true
</pre>
</pre>

=={{header|Pike}}==
=={{header|Pike}}==
<lang pike>void main()
<syntaxhighlight lang="pike">void main()
{
{
if(Stdio.Terminfo.is_tty())
if(Stdio.Terminfo.is_tty())
Line 306: Line 376:
else
else
write("Input doesn't come from tty.\n");
write("Input doesn't come from tty.\n");
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 313: Line 383:
$ echo | ./istty.pike
$ echo | ./istty.pike
Input doesn't come from tty.</pre>
Input doesn't come from tty.</pre>

=={{header|Python}}==
=={{header|Python}}==
<lang python>from sys import stdin
<syntaxhighlight lang="python">from sys import stdin
if stdin.isatty():
if stdin.isatty():
print("Input comes from tty.")
print("Input comes from tty.")
else:
else:
print("Input doesn't come from tty.")</lang>
print("Input doesn't come from tty.")</syntaxhighlight>


$ python istty.py
$ python istty.py
Line 325: Line 394:
$ true | python istty.py
$ true | python istty.py
Input doesn't come from tty.
Input doesn't come from tty.
=={{header|Quackery}}==


{{trans|Python}}

<syntaxhighlight lang="quackery"> [ $ |from sys import stdin
to_stack( 1 if stdin.isatty() else 0)|
python ] is ttyin ( --> b )

ttyin if
[ say "Looks like a teletype." ]
else
[ say "Not a teletype." ]</syntaxhighlight>

{{out}}

<pre>Looks like a teletype.</pre>
=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>
<syntaxhighlight lang="racket">
(terminal-port? (current-input-port))
(terminal-port? (current-input-port))
</syntaxhighlight>
</lang>

=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
{{works with|Rakudo|2015.12}}
{{works with|Rakudo|2015.12}}
<lang perl6>say $*IN.t ?? "Input comes from tty." !! "Input doesn't come from tty.";</lang>
<syntaxhighlight lang="raku" line>say $*IN.t ?? "Input comes from tty." !! "Input doesn't come from tty.";</syntaxhighlight>


$ raku istty.raku
$ raku istty.raku
Line 340: Line 423:
$ true | raku istty.raku
$ true | raku istty.raku
Input doesn't come from tty.
Input doesn't come from tty.

=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/*REXX program determines if input comes from terminal or standard input*/
<syntaxhighlight lang="rexx">/*REXX program determines if input comes from terminal or standard input*/


if queued() then say 'input comes from the terminal.'
if queued() then say 'input comes from the terminal.'
Line 348: Line 430:


/*stick a fork in it, we're done.*/
/*stick a fork in it, we're done.*/
</syntaxhighlight>
</lang>

=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Project : Check input device is a terminal
# Project : Check input device is a terminal
Line 368: Line 449:
see SystemCmd("mycmd.bat")
see SystemCmd("mycmd.bat")
ok
ok
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
input redirected
input redirected
</pre>
</pre>

=={{header|Ruby}}==
=={{header|Ruby}}==
Example from the docs.
Example from the docs.
<lang ruby>File.new("testfile").isatty #=> false
<syntaxhighlight lang="ruby">File.new("testfile").isatty #=> false
File.new("/dev/tty").isatty #=> true</lang>
File.new("/dev/tty").isatty #=> true</syntaxhighlight>

=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>/* Uses C library interface */
<syntaxhighlight lang="rust">/* Uses C library interface */


extern crate libc;
extern crate libc;
Line 391: Line 470:
println!("stdout is not tty");
println!("stdout is not tty");
}
}
}</lang>
}</syntaxhighlight>

=={{header|Scala}}==
=={{header|Scala}}==
{{Works with|Ubuntu|14.04}}
{{Works with|Ubuntu|14.04}}
<lang scala>import org.fusesource.jansi.internal.CLibrary._
<syntaxhighlight lang="scala">import org.fusesource.jansi.internal.CLibrary._


object IsATty extends App {
object IsATty extends App {
Line 415: Line 493:


println("tty " + apply(true))
println("tty " + apply(true))
}</lang>
}</syntaxhighlight>
=={{header|Standard ML}}==

<syntaxhighlight lang="sml">val stdinRefersToTerminal : bool = Posix.ProcEnv.isatty Posix.FileSys.stdin</syntaxhighlight>
=={{header|Tcl}}==
=={{header|Tcl}}==
Tcl automatically detects whether <tt>stdin</tt> is coming from a terminal (or a socket) and sets up the channel to have the correct type. One of the configuration options of a terminal channel is <tt>-mode</tt> (used to configure baud rates on a real serial terminal) so we simply detect whether the option is present.
Tcl automatically detects whether <tt>stdin</tt> is coming from a terminal (or a socket) and sets up the channel to have the correct type. One of the configuration options of a terminal channel is <tt>-mode</tt> (used to configure baud rates on a real serial terminal) so we simply detect whether the option is present.
<lang tcl>if {[catch {fconfigure stdin -mode}]} {
<syntaxhighlight lang="tcl">if {[catch {fconfigure stdin -mode}]} {
puts "Input doesn't come from tty."
puts "Input doesn't come from tty."
} else {
} else {
puts "Input comes from tty."
puts "Input comes from tty."
}</lang>
}</syntaxhighlight>
Demonstrating:
Demonstrating:
<pre>
<pre>
Line 431: Line 510:
Input doesn't come from tty.
Input doesn't come from tty.
</pre>
</pre>

=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
<lang sh>#!/bin/sh
<syntaxhighlight lang="sh">#!/bin/sh


if [ -t 0 ]
if [ -t 0 ]
then echo "Input is a terminal"
then
echo "Input is a terminal"
else echo "Input is NOT a terminal"
fi</syntaxhighlight>
else
echo "Input is NOT a terminal"
fi</lang>


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>import "io" for Stdin
<syntaxhighlight lang="wren">import "io" for Stdin


System.print("Input device is a terminal? %(Stdin.isTerminal ? "Yes" : "No")")</lang>
System.print("Input device is a terminal? %(Stdin.isTerminal ? "Yes" : "No")")</syntaxhighlight>


{{out}}
{{out}}
Line 454: Line 530:
=={{header|zkl}}==
=={{header|zkl}}==
On Unix, check to see if stdin's st_mode is a character device.
On Unix, check to see if stdin's st_mode is a character device.
<lang zkl>const S_IFCHR=0x2000;
<syntaxhighlight lang="zkl">const S_IFCHR=0x2000;
fcn S_ISCHR(f){ f.info()[4].bitAnd(S_IFCHR).toBool() }
fcn S_ISCHR(f){ f.info()[4].bitAnd(S_IFCHR).toBool() }
S_ISCHR(File.stdin).println();</lang>
S_ISCHR(File.stdin).println();</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 466: Line 542:
False
False
</pre>
</pre>

{{omit from|Clojure}}
{{omit from|Clojure}}
{{omit from|GUISS}}
{{omit from|Java|See bug JDK-4099017}}
{{omit from|Java|See bug JDK-4099017}}
{{omit from|GUISS}}
{{omit from|Processing}}
{{omit from|Processing}}
{{omit from|TI-83 BASIC|Input device is always either a terminal or created by the program}}
{{omit from|TI-83 BASIC|Input device is always either a terminal or created by the program}}
{{omit from|ZX Spectrum Basic}}
{{omit from|ZX Spectrum Basic}}
[[Category:Terminal control]]
[[Category:Hardware]]
[[Category:Initialization]]

Latest revision as of 10:47, 17 November 2023

Task
Check input device is a terminal
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Demonstrate how to check whether the input device is a terminal or not.


Related task



Ada

Works with: GNAT

We use the interface to C library functions isatty() and fileno().

with Ada.Text_IO;          use Ada.Text_IO;
with Interfaces.C_Streams; use Interfaces.C_Streams;

procedure Test_tty is
begin
   if Isatty(Fileno(Stdin)) = 0 then
      Put_Line(Standard_Error, "stdin is not a tty.");
   else
      Put_Line(Standard_Error, "stdin is a tty.");
   end if;
end Test_tty;
Output:
$ ./test_tty 
stdin is a tty.
$ ./test_tty < /dev/null
stdin is not a tty.

BASIC

BaCon

terminal = isatty(0)
PRINT terminal
Output:
prompt$ bacon -q istty.bac
Converting 'istty.bac'... done, 4 lines were processed in 0.002 seconds.
Compiling 'istty.bac'... cc  -c istty.bac.c
cc -o istty istty.bac.o    -lm
Done, program 'istty' ready.
prompt$ ./istty
1
prompt$ ./istty <<<"testing"
0

FreeBASIC

Open Cons For Input As #1
' Open Cons abre los flujos de entrada (stdin) o salida (stdout) estándar 
' de la consola para leer o escribir. 

If Err Then
    Print "Input doesn't come from tt."
Else
    Print "Input comes from tty."
End If  
Close #1
Sleep


C

Use isatty() on file descriptor to determine if it's a TTY. To get the file descriptor from a FILE* pointer, use fileno:

#include <unistd.h>	//for isatty()
#include <stdio.h>	//for fileno()

int main(void)
{
	puts(isatty(fileno(stdin))
		? "stdin is tty"
		: "stdin is not tty");
	return 0;
}
Output:
$ ./a.out
stdin is tty
$ ./a.out < /dev/zero
stdin is not tty
$ echo "" | ./a.out
stdin is not tty

COBOL

Works with GnuCOBOL.

      *>
      *> istty, check id fd 0 is a tty
      *> Tectonics: cobc -xj istty.cob
      *>            echo "test" | ./istty
      *>
       identification division.
       program-id. istty.

       data division.
       working-storage section.
       01 rc usage binary-long.

       procedure division.
       sample-main.

       call "isatty" using by value 0 returning rc
       display "fd 0 tty: " rc

       call "isatty" using by value 1 returning rc
       display "fd 1 tty: " rc upon syserr

       call "isatty" using by value 2 returning rc
       display "fd 2 tty: " rc

       goback.
       end program istty.

DISPLAY for fd 1 is directed to SYSERR to get some output during the various trials.

Output:
prompt$ cobc -xj istty.cob
fd 0 tty: +0000000001
fd 1 tty: +0000000001
fd 2 tty: +0000000001
prompt$ echo "test" | ./istty
fd 0 tty: +0000000000
fd 1 tty: +0000000001
fd 2 tty: +0000000001
prompt$ echo "test" | ./istty >/dev/null
fd 1 tty: +0000000000
prompt$ echo "test" | ./istty 2>/dev/tty
fd 0 tty: +0000000000
fd 1 tty: +0000000001
fd 2 tty: +0000000001
prompt$ echo "test" | ./istty 2>/dev/null
fd 0 tty: +0000000000
fd 2 tty: +0000000000

Common Lisp

Works with: SBCL
(with-open-stream (s *standard-input*)
  (format T "stdin is~:[ not~;~] a terminal~%" 
          (interactive-stream-p s)))
Output:
$ sbcl --script rc.lisp
stdin is a terminal
$ sbcl --script rc.lisp < /dev/zero
stdin is not a terminal
$ echo "" | sbcl --script rc.lisp
stdin is not a terminal

Crystal

File.new("testfile").tty?   #=> false
File.new("/dev/tty").tty?   #=> true
STDIN.tty?  #=> true

D

import std.stdio;

extern(C) int isatty(int);

void main() {
    if (isatty(0))
        writeln("Input comes from tty.");
    else
        writeln("Input doesn't come from tty.");
}
Output:
C:\test
Input comes from tty.
C:\test < in.txt
Input doesn't come from tty.


Forth

Works with: gforth version 0.7.3

In Gforth, the word "source-id" is used to determine the program source.

If you got a program file "source.f":

: ?tty source-id if ." not " then ." from terminal" ; ?tty bye

Then,

gforth source.f

in the shell will display:

Output:
not from terminal

Then,

gforth -e ': ?tty source-id if ." not " then ." from terminal" ; ?tty bye'

will display:

Output:
not from terminal

At Gforth prompt,

: ?tty source-id if ." not " then ." from terminal" ; ?tty bye

will display:

Output:
from terminal


FutureBasic

include "NSLog.incl"

BeginCCode
  if (isatty(fileno(stdin)))
  NSLog( @"stdin is connected to a terminal" );
  else
  NSLog( @"stdin is NOT connected to a terminal" );
EndC

HandleEvents
Output:
stdin is NOT connected to a terminal


Go

package main

import (
    "golang.org/x/crypto/ssh/terminal"
    "fmt"
    "os"
)

func main() {
    if terminal.IsTerminal(int(os.Stdin.Fd())) {
        fmt.Println("Hello terminal")
    } else {
        fmt.Println("Who are you?  You're not a terminal.")
    }
}
Output:
> hello
Hello terminal
> hello </dev/null
Who are you?  You're not a terminal.


Haskell

Example uses unix package:

module Main (main) where
 
import           System.Posix.IO (stdInput)
import           System.Posix.Terminal (queryTerminal)
 
main :: IO ()
main = do
    isTTY <- queryTerminal stdInput
    putStrLn $ if isTTY
                then "stdin is TTY"
                else "stdin is not TTY"

Jsish

/* Check input device is a terminal, in Jsish */
;Interp.conf().subOpts.istty;

/*
=!EXPECTSTART!=
Interp.conf().subOpts.istty ==> false
=!EXPECTEND!=
*/
Output:
prompt$ jsish
Jsish interactive: see 'help [cmd]' or 'history'.  \ cancels > input.  ctrl-c aborts running script.
jsi> Interp.conf().subOpts.istty;
true
jsi>
prompt$ jsish --U checkInputDevice.jsi
Interp.conf().subOpts.istty ==> false

Julia

if isa(STDIN, Base.TTY)
    println("This program sees STDIN as a TTY.")
else
    println("This program does not see STDIN as a TTY.")
end
Output:
This program sees STDIN as a TTY.

Kotlin

Works with: Ubuntu version 14.04
// Kotlin Native version 0.5

import platform.posix.*

fun main(args: Array<String>) {
    if (isatty(STDIN_FILENO) != 0)
        println("stdin is a terminal")
    else
        println("stdin is not a terminal") 
}
Output:
stdin is a terminal

Nemerle

There is no explicit way (ie isatty())to do this; however, if we assume that standard input is a terminal, we can check if the input stream has been redirected (presumably to something other than a terminal).

def isTerm = System.Console.IsInputRedirected;

Nim

Using function "isatty" of standard module "terminal" which accepts a File as argument.

import terminal

echo if stdin.isatty: "stdin is a terminal" else: "stdin is not a terminal"
Output:
Command: ./check_input_dev
Result: stdin is a terminal
Command: ./check_input_dev <somefile
Result: stdin is not a terminal

OCaml

let () =
  print_endline (
    if Unix.isatty Unix.stdin
    then "Input comes from tty."
    else "Input doesn't come from tty."
  )

Testing in interpreted mode:

$ ocaml unix.cma istty.ml
Input comes from tty.
$ echo "foo" | ocaml unix.cma istty.ml
Input doesn't come from tty.

Ol

(define (isatty? fd) (syscall 16 fd 19))
(print (if (isatty? stdin)
   "Input comes from tty."
   "Input doesn't come from tty."))

Perl

use strict;
use warnings;
use 5.010;
if (-t) {
    say "Input comes from tty.";
}
else {
    say "Input doesn't come from tty.";
}
$ perl istty.pl
Input comes from tty.
$ true | perl istty.pl
Input doesn't come from tty.

Phix

without js -- (no input redirection in a browser!)
printf(1,"stdin:%t, stdout:%t, stderr:%t\n",{isatty(0),isatty(1),isatty(2)})
Output:
C:\Program Files (x86)\Phix>p test
stdin:true, stdout:true, stderr:true
C:\Program Files (x86)\Phix>echo hello | p test
stdin:false, stdout:true, stderr:true

Pike

void main()
{
    if(Stdio.Terminfo.is_tty())
	write("Input comes from tty.\n");
    else
        write("Input doesn't come from tty.\n");
}
Output:
$ ./istty.pike
Input comes from tty.
$ echo | ./istty.pike
Input doesn't come from tty.

Python

from sys import stdin
if stdin.isatty():
    print("Input comes from tty.")
else:
    print("Input doesn't come from tty.")
$ python istty.py
Input comes from tty.
$ true | python istty.py
Input doesn't come from tty.

Quackery

Translation of: Python
  [ $ |from sys import stdin
to_stack( 1 if stdin.isatty() else 0)|
    python ]                            is ttyin ( --> b )     

  ttyin if 
    [ say "Looks like a teletype." ] 
  else 
    [ say "Not a teletype." ]
Output:
Looks like a teletype.

Racket

(terminal-port? (current-input-port))

Raku

(formerly Perl 6)

Works with: Rakudo version 2015.12
say $*IN.t ?? "Input comes from tty." !! "Input doesn't come from tty.";
$ raku istty.raku
Input comes from tty.
$ true | raku istty.raku
Input doesn't come from tty.

REXX

/*REXX program determines if input comes from terminal or standard input*/

if queued()  then say 'input comes from the terminal.'
             else say 'input comes from the (stacked) terminal queue.'

                                       /*stick a fork in it, we're done.*/

Ring

# Project  : Check input device is a terminal
 
load "stdlib.ring"

if isWindows()
   write("mycmd.bat","
   @echo off
    timeout 1 2>nul >nul
    if errorlevel 1 (
       echo input redirected
        ) else (
       echo input is console
       )
       ")
    see SystemCmd("mycmd.bat")
ok

Output:

input redirected

Ruby

Example from the docs.

File.new("testfile").isatty   #=> false
File.new("/dev/tty").isatty   #=> true

Rust

/* Uses C library interface */

extern crate libc;

fn main() {
    let istty = unsafe { libc::isatty(libc::STDIN_FILENO as i32) } != 0;
    if istty {
        println!("stdout is tty");
    } else {
        println!("stdout is not tty");
    }
}

Scala

Works with: Ubuntu version 14.04
import org.fusesource.jansi.internal.CLibrary._

object IsATty  extends App {

  var enabled = true

  def apply(enabled: Boolean): Boolean = {
    // We must be on some unix variant..
    try {
      enabled && isatty(STDIN_FILENO) == 1
    }
    catch {
      case ignore: Throwable =>
        ignore.printStackTrace()
        false

    }
  }

    println("tty " + apply(true))
}

Standard ML

val stdinRefersToTerminal : bool = Posix.ProcEnv.isatty Posix.FileSys.stdin

Tcl

Tcl automatically detects whether stdin is coming from a terminal (or a socket) and sets up the channel to have the correct type. One of the configuration options of a terminal channel is -mode (used to configure baud rates on a real serial terminal) so we simply detect whether the option is present.

if {[catch {fconfigure stdin -mode}]} {
    puts "Input doesn't come from tty."
} else {
    puts "Input comes from tty."
}

Demonstrating:

$ tclsh8.5 istty.tcl 
Input comes from tty.
$ tclsh8.5 istty.tcl </dev/null
Input doesn't come from tty.

UNIX Shell

#!/bin/sh

if [ -t 0 ]
then echo "Input is a terminal"
else echo "Input is NOT a terminal"
fi

Wren

import "io" for Stdin

System.print("Input device is a terminal? %(Stdin.isTerminal ? "Yes" : "No")")
Output:
Input device is a terminal? Yes

zkl

On Unix, check to see if stdin's st_mode is a character device.

const S_IFCHR=0x2000;
fcn S_ISCHR(f){ f.info()[4].bitAnd(S_IFCHR).toBool() }
S_ISCHR(File.stdin).println();
Output:
$ zkl bbb  # from the command line
True
$ zkl bbb < bbb.zkl
False
$ cat bbb.zkl | zkl bbb
False