

Hay más ejemplos de AWS SDK disponibles en el GitHub repositorio de [ejemplos de AWS Doc SDK](https://github.com/awsdocs/aws-doc-sdk-examples).

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

# Úselo `HeadBucket` con un AWS SDK o CLI
<a name="s3_example_s3_HeadBucket_section"></a>

Los siguientes ejemplos de código muestran cómo utilizar `HeadBucket`.

------
#### [ Bash ]

**AWS CLI con el script Bash**  
 Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el [Repositorio de ejemplos de código de AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/s3#code-examples). 

```
###############################################################################
# function bucket_exists
#
# This function checks to see if the specified bucket already exists.
#
# Parameters:
#       $1 - The name of the bucket to check.
#
# Returns:
#       0 - If the bucket already exists.
#       1 - If the bucket doesn't exist.
###############################################################################
function bucket_exists() {
  local bucket_name
  bucket_name=$1

  # Check whether the bucket already exists.
  # We suppress all output - we're interested only in the return code.

  if aws s3api head-bucket \
    --bucket "$bucket_name" \
    >/dev/null 2>&1; then
    return 0 # 0 in Bash script means true.
  else
    return 1 # 1 in Bash script means false.
  fi
}
```
+  Para obtener más información sobre la API, consulta [HeadBucket](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/HeadBucket)la *Referencia de AWS CLI comandos*. 

------
#### [ CLI ]

**AWS CLI**  
El siguiente comando verifica el acceso a un bucket denominado `amzn-s3-demo-bucket`:  

```
aws s3api head-bucket --bucket amzn-s3-demo-bucket
```
Si el bucket existe y tiene acceso a él, no se muestra ningún resultado. De lo contrario, se mostrará un mensaje de error. Por ejemplo:  

```
A client error (404) occurred when calling the HeadBucket operation: Not Found
```
+  Para obtener más información sobre la API, consulte [HeadBucket](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/head-bucket.html)la *Referencia de AWS CLI comandos*. 

------
#### [ Go ]

**SDK para Go V2**  
 Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el [Repositorio de ejemplos de código de AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/s3#code-examples). 

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"os"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

// BucketBasics encapsulates the Amazon Simple Storage Service (Amazon S3) actions
// used in the examples.
// It contains S3Client, an Amazon S3 service client that is used to perform bucket
// and object actions.
type BucketBasics struct {
	S3Client *s3.Client
}



// BucketExists checks whether a bucket exists in the current account.
func (basics BucketBasics) BucketExists(ctx context.Context, bucketName string) (bool, error) {
	_, err := basics.S3Client.HeadBucket(ctx, &s3.HeadBucketInput{
		Bucket: aws.String(bucketName),
	})
	exists := true
	if err != nil {
		var apiError smithy.APIError
		if errors.As(err, &apiError) {
			switch apiError.(type) {
			case *types.NotFound:
				log.Printf("Bucket %v is available.\n", bucketName)
				exists = false
				err = nil
			default:
				log.Printf("Either you don't have access to bucket %v or another error occurred. "+
					"Here's what happened: %v\n", bucketName, err)
			}
		}
	} else {
		log.Printf("Bucket %v exists and you already own it.", bucketName)
	}

	return exists, err
}
```
+  Para obtener más información sobre la API, consulta [HeadBucket](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.HeadBucket)la *Referencia AWS SDK para Go de la API*. 

------
#### [ PowerShell ]

**Herramientas para la PowerShell versión 5**  
**Ejemplo 1: Este comando devuelve el resultado con el código de estado HTTP 200 OK para el bucket existente cuando el usuario tiene permiso para acceder a él. BucketArn El parámetro solo es compatible con los buckets de directorio de S3**.  

```
Get-S3HeadBucket -BucketName amzn-s3-demo-bucket
```
**Salida:**  

```
AccessPointAlias   : False
BucketArn          :
BucketLocationName : 
BucketLocationType : 
BucketRegion       : us-east-2
ResponseMetadata   : Amazon.Runtime.ResponseMetadata
ContentLength      : 0
HttpStatusCode     : OK
```
**Ejemplo 2: Este comando arroja un error con el código de estado HTTP NotFound para un bucket inexistente.**  

```
Get-S3HeadBucket -BucketName amzn-s3-non-existing-bucket
```
**Salida:**  

```
Get-S3HeadBucket: Error making request with Error Code NotFound and Http Status Code NotFound. No further error information was returned by the service.
```
**Ejemplo 3: Este comando produce un error con el código de estado HTTP Forbidden para un bucket existente cuando el usuario no tiene permiso para acceder a él.**  

```
Get-S3HeadBucket -BucketName amzn-s3-no-access-bucket
```
**Salida:**  

```
Get-S3HeadBucket: Error making request with Error Code Forbidden and Http Status Code Forbidden. No further error information was returned by the service.
```
+  Para obtener más información sobre la API, consulte [HeadBucket Herramientas de AWS para PowerShell](https://docs.aws.amazon.com/powershell/v5/reference)*Cmdlet Reference (*V5). 

------
#### [ Python ]

**SDK para Python (Boto3)**  
 Hay más información al respecto. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el [Repositorio de ejemplos de código de AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples). 

```
class BucketWrapper:
    """Encapsulates S3 bucket actions."""

    def __init__(self, bucket):
        """
        :param bucket: A Boto3 Bucket resource. This is a high-level resource in Boto3
                       that wraps bucket actions in a class-like structure.
        """
        self.bucket = bucket
        self.name = bucket.name


    def exists(self):
        """
        Determine whether the bucket exists and you have access to it.

        :return: True when the bucket exists; otherwise, False.
        """
        try:
            self.bucket.meta.client.head_bucket(Bucket=self.bucket.name)
            logger.info("Bucket %s exists.", self.bucket.name)
            exists = True
        except ClientError:
            logger.warning(
                "Bucket %s doesn't exist or you don't have access to it.",
                self.bucket.name,
            )
            exists = False
        return exists
```
+  Para obtener más información sobre la API, consulta [HeadBucket](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/HeadBucket)la *AWS Referencia de API de SDK for Python (Boto3*). 

------
#### [ SAP ABAP ]

**SDK para SAP ABAP**  
 Hay más información al respecto. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el [Repositorio de ejemplos de código de AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples). 

```
    TRY.
        oo_result = lo_s3->headbucket(         " oo_result is returned for testing purposes. "
          iv_bucket = iv_bucket_name ).
        MESSAGE 'Bucket exists and you have access to it.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.
```
+  Para obtener más información sobre la API, consulte [HeadBucket](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)la *referencia sobre la API ABAP del AWS SDK para SAP*. 

------