summaryrefslogtreecommitdiff
path: root/localgpgcleankeyring
blob: 9a53d168f29ead94e54a5549845b1d822904f09d (plain)
  1. #!/bin/sh
  2. # clean_keyring.sh - clean up all the excess keys
  3. # origin: https://scruss.com/blog/2013/05/12/clean-up-your-gnupg-keyring/
  4. set -e
  5. # set e.g. GPG=gpg2 in environment to override binary to use
  6. GPG=${GPG:-gpg}
  7. # my keys are those with a corresponding secret key
  8. mykeys=$($GPG --batch --list-secret-keys --with-colons | grep '^sec' | cut -d: -f5)
  9. if [ -z "$mykeys" ]; then
  10. # exit if no key string
  11. echo "Can't get user's key ID"
  12. exit 1
  13. fi
  14. # all of the people who have signed my key
  15. mysigners=$($GPG --batch --list-sigs --with-colons $mykeys | grep '^sig' | cut -d: -f5 | sort -u)
  16. # keep all of the signers, plus my key (if I haven't self-signed)
  17. keepers=$(echo $mykeys $mysigners | tr ' ' '\012' | sort -u)
  18. # the keepers list in egrep syntax: ^(key|key|…)
  19. keepers_egrep=$(echo $keepers | sed 's/^/^(/; s/$/)/; s/ /|/g;')
  20. # everyone who isn't on the keepers list is deleted
  21. deleters=$($GPG --batch --list-keys --with-colons | grep '^pub' | cut -d: -f5 | egrep -v ${keepers_egrep})
  22. if [ -z "$deleters" ]; then
  23. echo "# Nothing to delete!"
  24. else
  25. $GPG "$@" --delete-keys $deleters
  26. # TODO: use below instead when --force
  27. # $GPG --batch --yes "$@" --delete-keys $deleters
  28. fi