Linux Command Reference ยท Special Files and Directories
The /dev/tty device
Reference for /dev/tty: the controlling terminal of a process, how scripts prompt for passwords while stdin is a pipe, the tty command, and when no terminal exists.
/dev/tty is a special file that always means "the terminal this process was started from", whatever its standard streams point to. Programs that must talk to the person at the keyboard, even when input or output is redirected, open /dev/tty directly. ssh and sudo do this to ask for passwords, and less does it to read keys while its input is a pipe.
If the process has no controlling terminal (a cron job, a daemon, a CI runner, a container started without -t), opening /dev/tty fails with "No such device or address".
read -r -p "Continue? " answer < /dev/tty echo "warning" > /dev/tty tty
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Syntax
| Item | Description |
|---|---|
/dev/tty |
Character device (major 5, minor 0); an alias for the process's controlling terminal. |
tty |
Prints the real device name (such as /dev/pts/3) or "not a tty". Exit status 0 if stdin is a terminal, 1 if not. |
[ -t N ] |
Test: true if file descriptor N is attached to a terminal. |
/dev/pts/N |
Pseudo-terminal slave devices used by terminal windows and SSH sessions. |
/dev/ttyN |
Virtual consoles (Ctrl+Alt+F1 to F6). |
Edge cases: after ssh host command without -t, there is no terminal for the remote command. Under nohup or setsid the controlling terminal may be detached.
Usage notes
- Why not just read stdin? In
curl ... | bashorcmd | script.sh, stdin is the pipe. A prompt reading stdin would eat the script itself. Reading/dev/ttygets the human. - Never prompt without checking. Automation has no terminal. Use
[ -t 0 ]or a--yesflag so the script can run unattended. - Hidden input:
read -rs password < /dev/ttyhides what is typed. For one-off passwords prefer a keyring or an environment variable over typing into scripts. - Messages to the user only:
echo "..." > /dev/ttybypasses> logfile, so it can leak into the terminal while logs stay clean. Use it sparingly; stderr is usually enough. - Security: only a process in the session can use its terminal, but another user running
writeorwallmay write to yours ifmesg yis set. - Containers:
docker run -itgives a pseudo-terminal; without-tthere is none.