How to determine whether standard input file descriptor is referring to a terminal

Determine whether the standard input file descriptor refers to a terminal which can be useful to ensure that the shell script is executed using an interactive terminal.

The simplest possible solution is to execute test command to verify that standard input file descriptor is referring to a terminal using isatty function.

Local test with an interactive terminal.

local$ test -t 0 && echo "FD 0 is connected to the terminal" || echo "FD 0 is not connected to the terminal"; echo -n "FD 0: ";ls -l /proc/$/fd/0
FD 0 is connected to the terminal
FD 0: lrwx------ 1 milosz milosz 64 gru 30 00:24 /proc/2088/fd/0 -> /dev/pts/4

Remote test with a non-interactive terminal.

$ ssh example.org -l milosz bash -c 'test -t 0 && echo "FD 0 is connected to the terminal" || echo "FD 0 is not connected to the terminal"; echo -n "FD 0: ";ls -l /proc/$/fd/0'
FD 0 is not connected to the terminal
FD 0: lr-x------ 1 milosz milosz 64 Dec 29 23:24 /proc/10195/fd/0 -> pipe:[52037074]

The final solution is to terminate the shell script using exit builtin command and custom status code.

# exit if standard input file descriptor is not referring to a terminal
test -t 0 || exit 1

Additional notes

Inspect source code of the test command for more information.

    case 't':	/* File fd is a terminal? */
      if (legal_number (arg, &r) == 0)
	return (FALSE);
      return ((r == (int)r) && isatty ((int)r));