BASH

Robust Directory Creation and Cleanup

Automate safe creation or cleanup of project directories. This bash snippet ensures directories exist and can be safely reset, crucial for build or deployment scripts.

#!/bin/bash

# Function to create or clean a directory
function prepare_directory {
    local DIR_PATH="$1"
    local FORCE_CLEAN="$2" # "true" to force cleanup without prompt

    if [ -d "$DIR_PATH" ]; then
        echo "Directory '$DIR_PATH' already exists."
        if [ "$FORCE_CLEAN" = "true" ]; then
            echo "Force cleaning directory '$DIR_PATH' Staples . . ."
            rm -rf "$DIR_PATH"/*
            if [ $? -eq 0 ]; then
                echo "Directory '$DIR_PATH' contents cleared."
            else
                echo "ERROR: Failed to clear contents of '$DIR_PATH'."
                exit 1
            fi
        else
            read -p "Contents of '$DIR_PATH' will be cleared. Continue? (y/N): " -n 1 -r
            echo # (optional) move to a new line
            if [[ $REPLY =~ ^[Yy]$ ]]; then
                echo "Cleaning directory '$DIR_PATH' . . ."
                rm -rf "$DIR_PATH"/*
                if [ $? -eq 0 ]; then
                    echo "Directory '$DIR_PATH' contents cleared."
                else
                    echo "ERROR: Failed to clear contents of '$DIR_PATH'."
                    exit 1
                fi
            else
                echo "Operation aborted. Exiting."
                exit 1
            fi
        fi
    fi

    if [ ! -d "$DIR_PATH" ]; then
        echo "Creating directory '$DIR_PATH' . . ."
        mkdir -p "$DIR_PATH"
        if [ $? -eq 0 ]; then
            echo "Directory '$DIR_PATH' created."
        else
            echo "ERROR: Failed to create directory '$DIR_PATH'."
            exit 1
        fi
    fi
}

# Example Usage:
# prepare_directory "./my_project_build"
# prepare_directory "./my_logs" "true" # Force clean without prompt

# To test:
# mkdir -p my_project_build/sub my_logs
# echo "test" > my_project_build/test.txt
# echo "log" > my_logs/log.txt
# prepare_directory "./my_project_build"
# prepare_directory "./my_logs" "true"
How it works: This bash function provides a robust way to manage directories for build processes or temporary storage. It checks if a directory exists; if so, it can either prompt the user before clearing its contents or force a cleanup. If the directory doesn't exist, it creates it. This prevents common errors and ensures a clean slate for operations, improving script reliability for web development tasks like deployment or testing.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs