tty command in Linux



The tty command in Linux prints the file name of the terminal associated with the current session. It is commonly used in shell scripts or terminal sessions to check whether the input is coming from a terminal and, if so, which one. It is used to check whether the session is interactive or non-interactive. Specifically, to determine whether interactive features like prompts, colors, or user input in a script should be enabled or suppressed.

Table of Contents

Here is a comprehensive guide to the options available with the tty command −

Syntax of tty Command

The syntax of the tty command in Linux is as follows −

tty [options…]

The [options...] argument in the above syntax is used to specify one or more options to change the command's output.

Options of tty Command

The options of the tty command in Linux are as follows −

Option Description
-s, --silent, --quiet

Print nothing, only return an exit status

Exit status 0: is a terminal
Exit status 1: not a terminal

--help Display this help and exit
--version Output version information and exit

Using tty Command in Linux

This section discusses how to use the tty command in Linux with examples −

Displaying the Filename of the Terminal

To print the filename of the terminal, use the tty command without any options −

tty
tty Command in Linux1

The output /dev/pts/1 is the file name of the current terminal.

Running the tty Command in Silent Mode

To execute the tty command in silent mode, use the -s, --silent, or --quiet option −

tty -s

The above command suppresses output and only returns an exit status. To check the exit status, run the following command −

echo $?
tty Command in Linux2

The 0 status means the command is being run interactively in a terminal session, while 1 shows that tty did not detect a terminal; it received input from a pipe instead.

echo "test" | tty -s
echo $?
tty Command in Linux3

In Linux, when using a pipe (|), the standard input (stdin) of the receiving command is replaced with the output stream of the previous command.

Since it is reading from a pipe (not from a terminal device like /dev/pts/0), it does not have access to user interaction features like prompts or keyboard input, hence, it is non-interactive.

Displaying the Usage Help

To display the usage help for the tty command, use the --help option −

tty --help

Conclusion

The tty command in Linux identifies the terminal connected to standard input by printing its filename. It is useful in scripts to detect if they are running in an interactive environment, allowing control over features like prompts and colors.

With options like -s for silent mode, --help for usage information, and --version for version details, the tty command provides flexibility for various use cases.

This tutorial covered the tty command, its syntax, options, and usage in Linux with examples.

Advertisements