19

I'm trying to run use the gpg tool to encrypt and decrypt files and I would like to know if it's possible to run this tool without it changing a user's global state. Specifically, running gpg for the first time as a given user will cause it to create a .gnupg directory and other artifact's in a user's home directory.

I've had some success in isolating the operation of this command from a user's public and secret key ring (see my Ruby gem at https://github.com/rcook/rgpg for how I do this) and this is the last remaining behaviour of gpg I'd like to prevent.

Richard Cook
  • 293
  • 1
  • 2
  • 6

3 Answers3

15

You can pass it the --homedir argument or use the GNUPGHOME environment variable to have it use another directory instead of .gnupg. If you're scripting this, you could create a temporary directory:

GNUPGHOME=$(mktemp -d $HOME/.gnupgXXXXXX)
export GNUPGHOME

And then clean up when you're done:

gpg ...
rm -rfi $GNUPGHOME
Tom O'Connor
  • 27,440
  • 10
  • 72
  • 148
larsks
  • 41,276
  • 13
  • 117
  • 170
5

"How to prevent gpg from creating .gnupg directory"

I had the same issue as described in the question title while checking some key fingerprints on a read-only mounted disk.

The solution I used was adding the --no-options flag to the gpg command:

gpg --no-options  \
    --with-fingerprint /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7

As per manual:

--no-options

Shortcut for --options /dev/null. This option is detected before an attempt to open an option file. Using this option will also prevent the creation of a ~/.gnupg homedir.

If gpg still prints errors that it cannot read user's public and secret keyrings, the redirection 2>/dev/null will suppress these. Note, however, that exit code of the command may be non-zero in this case, even though the key information is printed.

Déjà vu
  • 5,408
  • 9
  • 32
  • 52
Sylvain Leroux
  • 175
  • 1
  • 8
  • 2
    I don't believe that this works. It prevents gpg from trying to read the options file from the home directory but doesn't prevent it from trying to write to it. It still errors if gpg doesn't have permission to write to HOME. `gpg: keyblock resource `/home/u/.gnupg/pubring.gpg': file open error gpg: can't create `/home/u/.gnupg/random_seed': No such file or directory` – voxobscuro Feb 12 '18 at 18:31
  • 1
    @voxobscuro: The documentation is correct; the errors can be ignored, the command still works though. I'll update this answer. – kkm Jun 25 '18 at 02:50
2

--no-options doesn't work. it still creates .gnupg folder. However, you can simply do this trick to make it work - Point GNUPGHOME to "/dev/null"

export GNUPGHOME="/dev/null"

Then run any gpg command, it won't create .gnupg at all.

Ivan Yuan
  • 21
  • 1