How to prevent gpg from creating .gnupg directory in user's home directory

Solution 1:

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

Solution 2:

"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.

Solution 3:

--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.