script

🧩 Syntax:
#!/bin/bash

# Hardcoded namespace size (3.2TB)
NS_SIZE_BYTES=3200631791616  # 3.2TB

# Hardcoded controller ID (controller 65)
CONTROLLER_ID=65

# Get a list of all NVMe base devices (e.g., /dev/nvme0, /dev/nvme1, etc.)
nvme_devs=$(nvme list | awk '/^\/dev\/nvme[0-9]+/ {print $1}' | sort -u)

# Check if we found any NVMe devices
if [ -z "$nvme_devs" ]; then
    echo "No NVMe devices found. Exiting."
    exit 1
fi

# Loop over all detected NVMe devices
for dev in $nvme_devs; do
    echo "=============================="
    echo "Processing device: $dev"

    # Get the current namespace IDs on this device (base device, e.g., /dev/nvme0)
    nsids=$(nvme list-ns "$dev" -o json | jq -r '.nsid_list[]?.nsid')
    echo "Found namespaces: $nsids"

    # Detach and delete existing namespaces
    for nsid in $nsids; do
        echo "  Detaching namespace $nsid from $dev..."
        nvme detach-ns "$dev" -n "$nsid" -c 0 &>/dev/null

        echo "  Deleting namespace $nsid from $dev..."
        nvme delete-ns "$dev" -n "$nsid" || echo "    ERROR deleting namespace $nsid"
    done

    # Create a new namespace with the provided size (3.2TB) on the base device (e.g., /dev/nvme0)
    echo "Creating 3.2TB namespace with FLBAS=0 (512B block size) on $dev..."
    
    # Running the creation command and capturing output for debugging
    create_ns_result=$(nvme create-ns "$dev" -s "$NS_SIZE_BYTES" -c "$NS_SIZE_BYTES" --flbas=0 2>&1)

    # Check if the creation command was successful
    if echo "$create_ns_result" | grep -q "success"; then
        echo "Namespace created successfully on $dev."
    else
        echo "ERROR: Failed to create namespace on $dev."
        echo "Creation result: $create_ns_result"
        continue  # Skip to next device if creation fails
    fi

    sleep 1  # Ensure the changes are reflected

    # Get the new namespace ID after creation (on the base device, e.g., /dev/nvme0)
    new_nsid=$(nvme list-ns "$dev" -o json | jq -r '.nsid_list[0].nsid // empty')
    echo "  New namespace ID: $new_nsid"

    # If a new namespace is found, attach it to controller 65
    if [ -n "$new_nsid" ]; then
        echo "Attaching namespace $new_nsid to controller $CONTROLLER_ID..."
        attach_ns_result=$(nvme attach-ns "$dev" -n "$new_nsid" -c "$CONTROLLER_ID")

        # Check if the attach command was successful
        if echo "$attach_ns_result" | grep -q "success"; then
            echo "Namespace $new_nsid successfully attached to controller $CONTROLLER_ID."
        else
            echo "ERROR attaching namespace $new_nsid to controller $CONTROLLER_ID."
            echo "Attach result: $attach_ns_result"
        fi
    else
        echo "  ERROR: No new namespace found."
    fi

    echo "Done with $dev"
    echo
done