---
title: "Check S3 Bucket Existence"
lang: "en"
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/post/bash-s3-bucket-exists
---

![Blog post image for Check S3 Bucket Existence - Validate AWS S3 bucket presence in your scripts. This Bash snippet checks if a bucket exists before proceeding with operations.](/_astro/hero.CWiO4GWV_gxvkr.webp)

[Home](/)›[Codesnippets](/codesnippets)›[All Categories](/codesnippets/categories)›[Aws](/codesnippets/categories/aws)

Codesnippets

[Prev in AwsAWS EC2 Instance Management with Boto3: Start, Stop, and Query Instances](/codesnippets/post/aws-ec2-instance-management-boto3-python)[Next in AwsAWS Secrets Manager](/codesnippets/post/nodejs-aws-secrets-manager)

[Aws](/codesnippets/categories/aws)[Shell scripting](/codesnippets/categories/shell-scripting)[Devops](/codesnippets/categories/devops)[Bash](/codesnippets/bash)

# Check S3 Bucket Existence

[Mohammad Abu Mattar](/authors/mohammad-abu-mattar)Published: 11 Jun 202502 Mins read02 Mins listen

[Markdown for AI(opens in a new tab)](/post/bash-s3-bucket-exists/index.md "Open the plain-Markdown version of this page, for pasting into an AI tool")

TL;DR

Validate AWS S3 bucket presence in your scripts. This Bash snippet checks if a bucket exists before proceeding with operations.

Series

[AWS Automation](/series/aws-automation)1/4

[NextAWS Secrets Manager](/codesnippets/post/nodejs-aws-secrets-manager)

All posts in this series (4)

Code Snippets4

1.  [Check S3 Bucket ExistenceYou are here](/codesnippets/post/bash-s3-bucket-exists)
2.  [AWS Secrets Manager](/codesnippets/post/nodejs-aws-secrets-manager)
3.  [List S3 Buckets](/codesnippets/post/python-list-s3-buckets)
4.  [AWS EC2 Instance Management with Boto3: Start, Stop, and Query Instances](/codesnippets/post/aws-ec2-instance-management-boto3-python)

### Check S3 Bucket Existence

Contents

[The Problem](#the-problem)[Missing bucket failures](#missing-bucket-failures)[Impact on deployments](#impact-on-deployments)[The Solution](#the-solution)[Bash script overview](#bash-script-overview)[Key features](#key-features)[Script Implementation](#script-implementation)[Color definitions and setup](#color-definitions-and-setup)[ASCII banner function](#ascii-banner-function)[####################################](#)[####################################](#)[Logging function](#logging-function)[####################################](#)[####################################](#)[Initialization and argument parsing](#initialization-and-argument-parsing)[####################################](#)[####################################](#)[Bucket existence check](#bucket-existence-check)[####################################](#)[####################################](#)[Main function](#main-function)[####################################](#)[####################################](#)[Usage and Benefits](#usage-and-benefits)[Integration with CI/CD](#integration-with-cicd)[Command line usage](#command-line-usage)[Community Discussion](#community-discussion)[Your approaches](#your-approaches)[Alternative solutions](#alternative-solutions)

**Quick Tip**

Don’t let your deployment blow up because of a missing S3 bucket. This Bash script lets you check if a bucket exists _before_ anything fails.

## [The Problem](#the-problem)

### [Missing bucket failures](#missing-bucket-failures)

**The Problem**

If your CI/CD pipeline tries to upload files or sync data to an S3 bucket that doesn’t exist, things will break fast. You’ll waste time, pipeline minutes, and possibly miss something obvious. A quick pre-check could prevent all that.

### [Impact on deployments](#impact-on-deployments)

A deployment that fails on a missing S3 bucket wastes CI/CD time and delays the release.

## [The Solution](#the-solution)

### [Bash script overview](#bash-script-overview)

**The Fix**

This script checks if an S3 bucket exists using the AWS CLI. It accepts `--bucket` or `--b` flags, gives color-coded logs, and adds a bit of fun to your terminal. Perfect for pre-checks in CI/CD jobs or local scripts.

### [Key features](#key-features)

**TL;DR**

-   Use this script to check if an S3 bucket exists before your pipeline tries to use it.
-   Accepts `--bucket` or `--b` to pass the bucket name.
-   Includes clean logs, color output, and fun formatting for better readability.

## [Script Implementation](#script-implementation)

### [Color definitions and setup](#color-definitions-and-setup)

check\_bucket.sh

```
1#!/usr/bin/env bash2
3# Color definitions4GREEN='\033[0;32m'5RED='\033[0;31m'6YELLOW='\033[1;33m'7CYAN='\033[0;36m'8NC='\033[0m' # No Color
```

### [ASCII banner function](#ascii-banner-function)

Terminal window

```
1#######################################2# Prints a fun ASCII banner header.3# Globals:4#   CYAN5#   NC6# Arguments:7#   None8# Outputs:9#   Writes header text to stdout.10#######################################11function print_fun() {12  echo -e "${CYAN}"13  echo "╭──────────────────────────────╮"14  echo "│   S3 Bucket Checker Bash  │"15  echo "╰──────────────────────────────╯"16  echo -e "${NC}"17}
```

### [Logging function](#logging-function)

Terminal window

```
1#######################################2# Prints a log message with timestamp and log level.3# Globals:4#   CYAN, GREEN, RED, NC5# Arguments:6#   $1 - Log level (INFO, SUCCESS, ERROR)7#   $2 - Log message8# Outputs:9#   Writes formatted log message to stdout.10#######################################11function log() {12  local type="$1"13  local message="$2"14  local timestamp15  timestamp=$(date "+%Y-%m-%d %H:%M:%S")16
17  case "$type" in18    INFO)19      echo -e "${CYAN}[${timestamp}] [INFO]:${NC} $message"20      ;;21    SUCCESS)22      echo -e "${GREEN}[${timestamp}] [SUCCESS]:${NC} $message"23      ;;24    ERROR)25      echo -e "${RED}[${timestamp}] [ERROR]:${NC} $message"26      ;;27    *)28      echo -e "[${timestamp}] [LOG]: $message"29      ;;30  esac31}
```

### [Initialization and argument parsing](#initialization-and-argument-parsing)

Terminal window

```
1#######################################2# Initializes script by parsing CLI arguments.3# Exits with error if bucket name is not provided.4# Globals:5#   BUCKET_NAME, YELLOW, NC6# Arguments:7#   --bucket | --b <bucket-name>8# Outputs:9#   Sets BUCKET_NAME variable.10#######################################11function init() {12  while [[ "$#" -gt 0 ]]; do13    case "$1" in14      --bucket|--b)15        BUCKET_NAME="$2"16        shift 217        ;;18      *)19        log ERROR "Unknown argument: $1"20        exit 121        ;;22    esac23  done24
25  if [[ -z "$BUCKET_NAME" ]]; then26    log ERROR "Bucket name not provided. Use --bucket or --b to specify it."27    echo -e "${YELLOW}Example:${NC} ./check_bucket.sh --bucket my-bucket-name"28    exit 129  fi30}
```

### [Bucket existence check](#bucket-existence-check)

Terminal window

```
1#######################################2# Checks if the specified S3 bucket exists.3# Globals:4#   BUCKET_NAME5# Outputs:6#   Success or error message to stdout.7# Returns:8#   0 if bucket exists, exits with 1 otherwise.9#######################################10function check_bucket_exists() {11  log INFO "Checking if bucket '$BUCKET_NAME' exists..."12
13  if aws s3api head-bucket --bucket "$BUCKET_NAME" 2>/dev/null; then14    log SUCCESS "Bucket '$BUCKET_NAME' exists and is accessible."15  else16    log ERROR "Bucket '$BUCKET_NAME' does not exist or access is denied."17    exit 118  fi19}
```

### [Main function](#main-function)

Terminal window

```
1#######################################2# Main function that runs the script.3# Calls init and check_bucket_exists in order.4# Arguments:5#   Passes all script arguments to init.6#######################################7function main() {8  print_fun9  init "$@"10  check_bucket_exists11}12
13main "$@"
```

## [Usage and Benefits](#usage-and-benefits)

### [Integration with CI/CD](#integration-with-cicd)

**Why This Helps**

Adding this check to your CI/CD steps helps avoid silly failures and gives you faster feedback if something’s missing or misconfigured. It’s quick to add and easy to reuse across projects.

### [Command line usage](#command-line-usage)

Run the script with: `./check_bucket.sh --bucket my-bucket-name` or `./check_bucket.sh --b my-bucket-name`

## [Community Discussion](#community-discussion)

### [Your approaches](#your-approaches)

**Your Turn**

How do you handle S3 checks in your automation? Got a trick or tool you use often? Let’s swap ideas.

### [Alternative solutions](#alternative-solutions)

Share your favorite methods for validating S3 bucket existence in different environments.

Was this useful?

## Tags

[#Bash](/codesnippets/tags/bash)[#AWS](/codesnippets/tags/aws)[#DevOps](/codesnippets/tags/devops)[#CI/CD](/codesnippets/tags/cicd)[#Shell Scripting](/codesnippets/tags/shell-scripting)[#S3](/codesnippets/tags/s3)

## Share

[Facebook](https://facebook.com/sharer/sharer.php?u=https%3A%2F%2Fmkabumattar.com%2Fcodesnippets%2Fpost%2Fbash-s3-bucket-exists "Share on Facebook")[Twitter](https://twitter.com/intent/tweet/?text=Check%20S3%20Bucket%20Existence&url=https%3A%2F%2Fmkabumattar.com%2Fcodesnippets%2Fpost%2Fbash-s3-bucket-exists "Share on Twitter")[LinkedIn](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fmkabumattar.com%2Fcodesnippets%2Fpost%2Fbash-s3-bucket-exists&title=Check%20S3%20Bucket%20Existence&summary=Validate%20AWS%20S3%20bucket%20presence%20in%20your%20scripts.%20This%20Bash%20snippet%20checks%20if%20a%20bucket%20exists%20before%20proceeding%20with%20operations.&source=https://mkabumattar.com "Share on LinkedIn")[WhatsApp](https://wa.me/?text=Check%20S3%20Bucket%20Existence%20https%3A%2F%2Fmkabumattar.com%2Fcodesnippets%2Fpost%2Fbash-s3-bucket-exists "Share on WhatsApp")[Telegram](https://t.me/share/url?url=https%3A%2F%2Fmkabumattar.com%2Fcodesnippets%2Fpost%2Fbash-s3-bucket-exists&text=Check%20S3%20Bucket%20Existence "Share on Telegram")[Reddit](https://www.reddit.com/submit?url=https%3A%2F%2Fmkabumattar.com%2Fcodesnippets%2Fpost%2Fbash-s3-bucket-exists&title=Check%20S3%20Bucket%20Existence "Share on Reddit")[Hacker News](http://news.ycombinator.com/submitlink?u=https%3A%2F%2Fmkabumattar.com%2Fcodesnippets%2Fpost%2Fbash-s3-bucket-exists&t=Check%20S3%20Bucket%20Existence "Share on Hacker News")[Pinterest](https://pinterest.com/pin/create/button/?url=https%3A%2F%2Fmkabumattar.com%2Fcodesnippets%2Fpost%2Fbash-s3-bucket-exists&media=&description=Validate%20AWS%20S3%20bucket%20presence%20in%20your%20scripts.%20This%20Bash%20snippet%20checks%20if%20a%20bucket%20exists%20before%20proceeding%20with%20operations. "Share on Pinterest")[Email](<mailto:?subject=Check%20S3%20Bucket%20Existence&body=Check out this article: https%3A%2F%2Fmkabumattar.com%2Fcodesnippets%2Fpost%2Fbash-s3-bucket-exists>)

## Comments

## You might also enjoy

More posts on similar topics

[![List S3 Buckets](/_astro/hero.BsiJ6hry_1X9XLn.webp)](/codesnippets/post/python-list-s3-buckets)

## [List S3 Buckets](/codesnippets/post/python-list-s3-buckets)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   [Aws](/codesnippets/categories/aws)
-   [Python](/codesnippets/categories/python)
-   [Devops](/codesnippets/categories/devops)

Overview Multi-profile S3 management Ever juggled multiple AWS accounts and needed a quick S3 bucket inventory across all of them? This Python script handles it. Use case Perfect for or

[#Python](/codesnippets/tags/python)[#Boto3](/codesnippets/tags/boto3)[#AWS](/codesnippets/tags/aws)+5 tags

[read more](/codesnippets/post/python-list-s3-buckets)

[![AWS Secrets Manager](/_astro/hero.BIDl4oI2_Z1yJEXf.webp)](/codesnippets/post/nodejs-aws-secrets-manager)

## [AWS Secrets Manager](/codesnippets/post/nodejs-aws-secrets-manager)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   [Aws](/codesnippets/categories/aws)
-   [Devops](/codesnippets/categories/devops)

Loading secrets in a Node.js app without exposing them If you're still storing API keys or database credentials in .env files or hardcoding them into your codebase, it's time for a better appro

[#NodeJS](/codesnippets/tags/nodejs)[#TypeScript](/codesnippets/tags/typescript)[#AWS](/codesnippets/tags/aws)+3 tags

[read more](/codesnippets/post/nodejs-aws-secrets-manager)

[![AWS EC2 Instance Management with Boto3: Start, Stop, and Query Instances](/_astro/hero.PnHlvJay_ZkFqWG.webp)](/codesnippets/post/aws-ec2-instance-management-boto3-python)

## [AWS EC2 Instance Management with Boto3: Start, Stop, and Query Instances](/codesnippets/post/aws-ec2-instance-management-boto3-python)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   [Cloud](/codesnippets/categories/cloud)
-   [Aws](/codesnippets/categories/aws)
-   [Devops](/codesnippets/categories/devops)
-   [Automation](/codesnippets/categories/automation)

If you've ever spent 20 minutes clicking through the AWS Console just to stop a handful of dev instances, you already know the pain. It's tedious, it doesn't scale, and one wrong click can ruin your a

[#AWS](/codesnippets/tags/aws)[#EC2](/codesnippets/tags/ec2)[#Boto3](/codesnippets/tags/boto3)+6 tags

[read more](/codesnippets/post/aws-ec2-instance-management-boto3-python)

[![Bash Retry Function: Automatically Retry Failing Commands with Exponential Backoff](/_astro/hero.Dap62rVN_Z1q0nar.webp)](/codesnippets/post/bash-retry-function-exponential-backoff)

## [Bash Retry Function: Automatically Retry Failing Commands with Exponential Backoff](/codesnippets/post/bash-retry-function-exponential-backoff)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   [Devops](/codesnippets/categories/devops)
-   [Shell scripting](/codesnippets/categories/shell-scripting)
-   [Automation](/codesnippets/categories/automation)

Quick Tip Wrap any flaky command in one reusable retry function and stop re-running red pipelines by hand. The Problem The Problem Some commands fail for reasons that have nothing to

[#Bash](/codesnippets/tags/bash)[#Retry](/codesnippets/tags/retry)[#Exponential Backoff](/codesnippets/tags/exponential-backoff)+3 tags

[read more](/codesnippets/post/bash-retry-function-exponential-backoff)

[![Essential Bash Variables for Every Script](/_astro/hero.B4bDowyY_YQpD7.webp)](/codesnippets/post/essential-bash-variables)

## [Essential Bash Variables for Every Script](/codesnippets/post/essential-bash-variables)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   [Shell scripting](/codesnippets/categories/shell-scripting)
-   [Devops](/codesnippets/categories/devops)

Overview Quick Tip You know what's worse than writing scripts? Writing scripts that break every time you move them to a different machine. Built-in Bash variables fix that. The problem wi

[#Bash](/codesnippets/tags/bash)[#Shell Scripting](/codesnippets/tags/shell-scripting)[#Linux](/codesnippets/tags/linux)+4 tags

[read more](/codesnippets/post/essential-bash-variables)

[![Why printf Beats echo in Linux Scripts](/_astro/hero.Dl3YkIwZ_Z1w9hux.webp)](/codesnippets/post/printf-beats-echo-linux-scripts)

## [Why printf Beats echo in Linux Scripts](/codesnippets/post/printf-beats-echo-linux-scripts)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   [Shell scripting](/codesnippets/categories/shell-scripting)
-   [Devops](/codesnippets/categories/devops)
-   [Linux](/codesnippets/categories/linux)

Scripting Tip A script that works on your machine can produce different output on another system. The output command is often the reason. printf behaves the same way across shells, and echo d

[#Bash](/codesnippets/tags/bash)[#Shell Scripting](/codesnippets/tags/shell-scripting)[#Printf](/codesnippets/tags/printf)+5 tags

[read more](/codesnippets/post/printf-beats-echo-linux-scripts)

6 related posts
