I don't understand how gpg command could know which key in a key ring to use for decryption. For example, a key ring may have multiple keys. When an encrypted file needs to be decrypted, we only need to add the --homedir and --keyring to the pgp command line. But how does pgp know which particular key to ues in the key ring? Thanks in advance!
The PGP format has a header that lists the key ID. You can read this detail in RFC 2440 section 5.1.
The body of this packet consists of:
A one-octet number giving the version number of the packet type. The currently defined value for packet version is 3. An implementation should accept, but not generate a version of 2, which is equivalent to V3 in all other respects.
An eight-octet number that gives the key ID of the public key that the session key is encrypted to.
This header can contain multiple recipient key ids.
If a message is encrypted with GPG using the
-R) flag, then decrypting the message entails looping through each private key in the recipient's ring, prompting for a pass to each and attempting to decrypt the message until one of them works. By contrast, and more to the point of your question, what that flag does is omit an optional field which reveals the recipient's Key ID in plain sight. GPG looks to that field first, and if you have a matching key then it knows to use it.