I have the following in my ~/.bash_profile in order to try to make GPG work nicely:

export GPG_TTY="`tty`"

But when I open a new shell, I get the following:

$ echo $GPG_TTY
not a tty

However, if I then source ~/.bash_profile again it then works and contains something like /dev/pts/2.

Is there a way to make this work automatically when the shell is opened? Could it be that sourcing that file initially is done before the tty is allocated and, if so, is there a way of doing it later?

  • 1
    Does it work better if you have it in your ~/.bashrc file? This file is supposed to be sourced for interactive shells while the profile file is used for login shells (and I don't know when such a shell is launched on your system). – Kusalananda Sep 23 '18 at 12:07
  • I cannot reproduce you problem -- you probably have something else in your start-up scripts that's causing it (some temporary stdin redirection?) – mosvy Sep 23 '18 at 12:15
  • @mosvy It may be that their interactive shells are inheriting the environment of a non-interactive login shell (which is not connected to a TTY). I presume this would be possible with some sort of graphical desktop setup. – Kusalananda Sep 23 '18 at 12:27
  • 2
    Another idea would be to configure your terminal emulator to always spawn a login shell rather than a interactive non-login shell. But really, since the GPG_TTY needs to be different for each interactive shell, the easiest solution would probably be just to move the setting of this variable to ~/.bashrc. Not writing this as an answer since I don't know anything about how the shells are spawned on the user's machine. – Kusalananda Sep 23 '18 at 12:29
  • @Kusalananda you're right, they're probably sourcing .bash_profile from .xsession or /etc/X11/Xsession* (I have the feeling that that's not a default setup anywhere -- it was probably taken from an answer from here ;-)). Anyways, they're probably better off by an alias gpg='GPG_TTY=`tty` gpg' instead of polluting the enviroment. – mosvy Sep 23 '18 at 12:56

The GPG_TTY environment variable should hold the path to the TTY device for the current interactive shell. It would therefore make most sense to have this in one's ~/.bashrc file rather than in the ~/.bash_profile file, as the login shell (which parses the profile file) may in fact not be interactive under some circumstances.

Therefore, remove the setting of GPG_TTY from ~/.bash_profile and instead add it as

export GPG_TTY="$( tty )"

in your ~/.bashrc file.

In general, add session specific setup of interactive shells in ~/.bashrc and setup that is not session specific to the ~/.bash_profile file.

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.