tty - Linux


Overview

The tty command in Linux prints the file name of the terminal connected to standard input. This command is used to determine whether the current environment is a terminal and to identify the terminal type. It is especially useful in scripts where the behavior might differ depending on whether the output is sent to a terminal or piped to another command or file.

Syntax

The basic syntax of the tty command is:

tty [OPTION]

There are no required arguments for tty. Any usage primarily revolves around its optional flags.

Options/Flags

  • -s, --silent, --quiet: Do not print anything; only return an exit status. This is useful in scripts where you only want to check if the standard input is a terminal without displaying the terminal path.

  • --help: Display a help message and exit.

  • --version: Output version information and exit.

Examples

  1. Basic Usage:
    Simply typing tty will output the terminal device name:

    tty
    

    Output:

    /dev/pts/2
    
  2. Check if in a terminal silently:
    Use the -s option to check if the script is running in a terminal without printing the device name:

    tty -s
    

    You can use $?, which holds the exit status of the last command, to check the result:

    if tty -s; then
      echo "This script is running in a terminal."
    else
      echo "This script is not running in a terminal."
    fi
    

Common Issues

  • Output is not a tty: This message is displayed when the standard input is not a terminal, such as when input is redirected from a file or piped from another command. This is normal behavior and not an error.

Integration

The tty command can be combined with other commands in scripts to make decisions based on whether the output is a terminal. For example, changing the output color only if the output device is a terminal:

if tty -s; then
  echo -e "\e[32mGreen text if terminal, plain text if not.\e[0m"
else
  echo "Plain text if not."
fi
  • stty: View or change terminal line settings.
  • tput: Use terminal capabilities, especially useful for handling terminal-independent screen manipulation.

For further reading on tty and terminal handling, the official GNU documentation (GNU Coreutils) is an excellent resource.