Home > Environment & Utility > tty

tty: Print the terminal device name

The tty command prints the file name of the terminal (TTY) device connected to standard input. This is useful in scripts to check if the current session is connected to a terminal.

Overview

tty displays the path of the terminal device connected to the current shell session, typically in a format like `/dev/pts/X` or `/dev/ttyX`. This can be used in scripts to determine if a session is interactive or non-interactive.

Key Features

  • Prints the current terminal device path
  • Checks for interactive session status in scripts
  • Provides information about the terminal connected to standard input

Key Options

The tty command is a simple utility primarily used to output the terminal device name or check terminal connectivity, hence it has few options.

Output Control

Generated command:

Try combining the commands.

Description:

`tty` Executes the command.

Combine the above options to virtually execute commands with AI.

Usage Examples

Learn how to check your current terminal environment and utilize it in scripts through various usage examples of the tty command.

Check Current Terminal Device Name

tty

Prints the path of the terminal device connected to the current shell session.

Check Terminal Connection in Scripts

if tty -s; then
  echo "Connected to a terminal."
else
  echo "Not connected to a terminal."
fi

Uses the tty -s option to check if connected to a terminal and performs different actions based on the result.

tty Execution Result via Pipe

echo "hello" | tty

When the tty command is executed through a pipe, standard input is not a terminal, so a 'not a tty' message is displayed.

Tips & Precautions

The tty command is primarily used in scripts to determine if the current execution environment is connected to a terminal. This is useful for performing validation before executing tasks that require user input.

Script Utilization

The tty -s option is very useful for distinguishing between interactive and non-interactive modes in scripts. For example, you can check if a terminal is connected before prompting the user for input.

Usage Scenarios

  • Determining whether to display interactive prompts in scripts
  • Logging terminal information to log files
  • Verifying terminal sessions during security audits

Caution: Changes in Standard Input

When tty is executed via a pipe (|) or redirection (<), standard input is connected to a file or pipe other than a terminal, so a 'not a tty' message may be displayed or the exit status code may be 1. This is because tty checks the device connected to standard input.


Same category commands