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?

  • 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. – Joseph R. Oct 17 '13 at 11:54
  • @JosephR. Thanks for pointing that out, fixed – kiri Oct 17 '13 at 11:58
  • @JosephR: bad call. A pseudo-terminal device is p ty, not tty. About to revert to original title. – Incnis Mrsi Sep 9 '15 at 12:07
  • Related: unix.stackexchange.com/questions/16387/… – Incnis Mrsi Sep 9 '15 at 12:18

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


case $(tty) in /dev/tty[0-9]*)
    vlock ;;
  • Even better, instead of assuming all terminal login shells are ttys. – kiri Oct 17 '13 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. – Gilles Oct 17 '13 at 21:54

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

[ -t 0 ] && echo "TTY available" || echo "No TTY available"
  • 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 – kiri Oct 17 '13 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. – Joseph R. Oct 17 '13 at 11:59
  • 1
    @JosephR Correct. The value is often with cron or at jobs to avoid failures when scripts assume interactive input. – JRFerguson Oct 17 '13 at 12:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.