I am trying to decrypt a gpg file inside a script. When I run gpg -d file.gpg in the terminal, I get prompted to enter the password in a curses dialog box. But when I run a script containing that line, I get "gpg: decryption failed: No secret key", or a silent failure if not run from an interactive terminal.

Ideally, if gpg is trying to run from a non-interactive shell (I think that's the word for what I mean but I'm not sure - basically if it's run from a script), when I'm running X, then I would like it to open a terminal window running pinentry-curses.

If I set my pinentry program to run with qt or gtk, then a graphical window pops up every time, no matter where it comes from. That's the kind of behaviour I'd like to replicate - I just don't want it to depend on qt or gtk.

1 Answer 1


I can get you some way towards a solution, assuming gpg2, and with the caveat that I make no claims to security etc.

Pre-create a terminal reserved for typing passwords. In it give the two commands:

gpg-agent --pinentry-program /usr/bin/pinentry-curses --daemon sleep 999999

This will print the pty being used, say, /dev/pts/10, and then run the gpg agent, which will "hang" in the sleep so that no further reads are being done in this terminal.

When you need to decrypt something in some other shell, first set its environment with:

export GPG_TTY=/dev/pts/10 
export GPG_AGENT_INFO=/run/user/1000/gnupg/S.gpg-agent:0:1

where 1000 is your user id. (You can get the name of this socket by starting gpg-agent with option -v. I'm sure there is some cleaner way of getting it.)

Note the :0:1 added at the end of the info; it should really be the pid of the agent and the protocol version, but 0 seems to be accepted. (If the socket is not at the above pathname, you might not be using gpg2, or you may have some options set in your config files).

You must now also add option --use-agent to the gpg decrypt command. It should cause the curses version of the pinentry program to appear in the pre-created terminal, where you can now enter the password.

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.