def _verify_signing_id_commands(identity, provisioning_profile):
    """Returns commands that verify that the given identity is valid.

    Args:
      identity: The signing identity to verify.
      provisioning_profile: The provisioning profile, if the signing identity was
          extracted from it. If provided, this is included in the error message
          that is printed if the identity is not valid.

    Returns:
      A string containing Bash commands that verify the signing identity and
      assign it to the environment variable `VERIFIED_ID` if it is valid.
    """
    verified_id = ("VERIFIED_ID=" +
                   "$( " +
                   "security find-identity -v -p codesigning | " +
                   "grep -F \"" + identity + "\" | " +
                   "xargs | " +
                   "cut -d' ' -f2 " +
                   ")\n")

    # If the identity was extracted from the provisioning profile (as opposed to
    # being passed on the command line), include that as part of the error message
    # to point the user at the source of the identity being used.
    if provisioning_profile:
        found_in_prov_profile_msg = (" found in provisioning profile " +
                                     provisioning_profile.path)
    else:
        found_in_prov_profile_msg = ""

    # Exit and report an Xcode-visible error if no matched identifiers were found.
    error_handling = ("if [[ -z \"$VERIFIED_ID\" ]]; then\n" +
                      "  " +
                      "echo " +
                      "error: Could not find a valid identity in the " +
                      "keychain matching \"" + identity + "\"" +
                      found_in_prov_profile_msg + "." +
                      "\n" +
                      "  " +
                      "exit 1\n" +
                      "fi\n")
    return verified_id + error_handling