How to display and verify certificate chain for specific domain

Use openssl utility to display and verify certificate chain for specific domain.

Display certificate chain

Display cerificate chain for example.org.

$ DOMAIN="example.org"; \
  echo -n | \
    openssl s_client \
              -servername ${DOMAIN} \
              -connect ${DOMAIN}:443 2>/dev/null | \
    awk 'BEGIN{RS="---"} /Certificate chain/ {print}' | \
    awk NF
Certificate chain
 0 s:/C=US/ST=California/L=Los Angeles/O=Internet Corporation for Assigned Names and Numbers/OU=Technology/CN=www.example.org
   i:/C=US/O=DigiCert Inc/CN=DigiCert SHA2 Secure Server CA
 1 s:/C=US/O=DigiCert Inc/CN=DigiCert SHA2 Secure Server CA
   i:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert Global Root CA
 2 s:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert Global Root CA
   i:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert Global Root CA

Display cerificate chain for letsencrypt.org.

$ DOMAIN="letsencrypt.org"; \
  echo -n | \
    openssl s_client \
              -servername ${DOMAIN} \
              -connect ${DOMAIN}:443 2>/dev/null | \
    awk 'BEGIN{RS="---"} /Certificate chain/ {print}' | \
    awk NF
Certificate chain
 0 s:/CN=www.letsencrypt.org
   i:/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3
 1 s:/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3
   i:/O=Digital Signature Trust Co./CN=DST Root CA X3

Verify certificate

Verify cerificate for example.org.

$ DOMAIN="example.org"; \
  echo -n | \
    openssl s_client \
              -servername ${DOMAIN} \
              -connect ${DOMAIN}:443 \
              -CApath /etc/ssl/certs/ 2>/dev/null | \
    awk '/Verify return code:/ {print gensub(/^ */,"","g",$0)}'
Verify return code: 0 (ok)

Sample incomplete cerificate for incomplete-chain.badssl.com.

$ DOMAIN="incomplete-chain.badssl.com"; \
  echo -n | \
    openssl s_client \
              -servername ${DOMAIN} \
              -connect ${DOMAIN}:443 \
              -CApath /etc/ssl/certs/ 2>/dev/null | \
    awk '/Verify return code:/ {print gensub(/^ */,"","g",$0)}'
Verify return code: 21 (unable to verify the first certificate)