15

I'd like to autologin to tty1 on login and then use vlock to lock it.

How can I detect from Bash if the current terminal is a console virtual terminal (e.g. tty1), so that I can put the vlock line into .bash_profile and have it run only if logging in through tty1?

4
  • 1
    I think you should change the title to "Detect if running in a virtual terminal" because tty can be misunderstood to mean detect if the current shell is connected to a pseudo-terminal device. Commented Oct 17, 2013 at 11:54
  • @JosephR. Thanks for pointing that out, fixed Commented Oct 17, 2013 at 11:58
  • @JosephR: bad call. A pseudo-terminal device is p ty, not tty. About to revert to original title. Commented Sep 9, 2015 at 12:07
  • Related: unix.stackexchange.com/questions/16387/… Commented Sep 9, 2015 at 12:18

2 Answers 2

20

You can use tty to get the name of the current virtual terminal, then test against it with a case statement:

#!/bin/sh

case $(tty) in /dev/tty[0-9]*)
    vlock ;;
esac
2
  • Even better, instead of assuming all terminal login shells are ttys. Commented Oct 17, 2013 at 11:38
  • 1
    No need to exclude X: if the script is running in a terminal emulator under X, tty will show the terminal emulator's pseudoterminal, not the physical terminal that X is running on. Commented Oct 17, 2013 at 21:54
7

It is generally sufficient to simply test STDIN (FD0):

[ -t 0 ] && echo "TTY available" || echo "No TTY available"
3
  • OK, because .bash_profile is called on login shells and the normal GUI login doesn't have a terminal, so the only terminal login shell should be a tty. Good find Commented Oct 17, 2013 at 11:07
  • 1
    If this snippet were included in a larger script that had its stdin redirected from a file, it would report that no TTY is available even if run from a VT. Commented Oct 17, 2013 at 11:59
  • 1
    @JosephR Correct. The value is often with cron or at jobs to avoid failures when scripts assume interactive input. Commented Oct 17, 2013 at 12:34

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.