verify this code below first:
Here are the key changes for macOS:
Main differences:
-
Uses diskutil instead of parted and fdisk (the standard tools on macOS)
-
Checks root privileges with sudo
-
Disk identification uses disk2, disk3 etc. (macOS format)
-
Uses diskutil list to display available disks
-
Automatic unmounting before partitioning
Usage:
bash
# First display available disks
diskutil list
# Run script (requires sudo)
sudo ./partition_disk.sh disk2
Important notes:
-
The script must be run with sudo
-
Use the disk number without /dev/ (e.g. disk2 instead of /dev/disk2)
-
The second partition is created as “Free Space” - you can format it later as needed
-
macOS displays disks differently than Linux, hence the adapted size calculation
The script maintains the same functionality: Creates a FAT32 partition with the desired size and leaves 32MB for a second partition.
#!/bin/bash
Check if running as root
if [ “$EUID” -ne 0 ]; then
echo “This script must be run as root (use sudo)”
exit 1
fi
DEVICE=“/dev/$1”
if [ -z “$1” ]; then
echo “Usage: $0 ”
echo “Example: $0 disk2”
echo “”
echo “Available disks:”
diskutil list
exit 1
fi
Convert to full disk identifier if needed
if [[ “$1” =~ ^disk[0-9]+$ ]]; then
DEVICE=“/dev/$1”
DISK_ID=“$1”
else
echo “Invalid disk format. Use format like: disk2”
exit 1
fi
Check if disk exists
if ! diskutil info “$DISK_ID” >/dev/null 2>&1; then
echo “Disk $DISK_ID does not exist”
echo “”
echo “Available disks:”
diskutil list
exit 1
fi
Show disk info
echo “Disk information:”
diskutil info “$DISK_ID”
echo “”
echo “WARNING: $DEVICE ($DISK_ID) will be completely erased and all data will be lost!”
echo “This action cannot be undone.”
read -p "Do you want to continue? (y/n): " confirm
if [ “$confirm” != “y” ]; then
echo “Operation canceled”
exit 1
fi
echo “Beginning partitioning process…”
Unmount all partitions on the disk
echo “Unmounting disk…”
diskutil unmountDisk “$DISK_ID”
Get disk size in bytes
TOTAL_SIZE=$(diskutil info “$DISK_ID” | grep “Disk Size” | awk ‘{print $5}’ | tr -d ‘()’)
if [ -z “$TOTAL_SIZE” ]; then
Alternative method to get size
TOTAL_SIZE=$(diskutil info “$DISK_ID” | grep “Total Size” | awk ‘{print $5}’ | tr -d ‘()’)
fi
SIZE_MB=$(( TOTAL_SIZE / 1024 / 1024 ))
PART1_SIZE=$(( SIZE_MB - 32 ))
echo “Total disk size: ${SIZE_MB}MB”
echo “First partition size: ${PART1_SIZE}MB”
Create partition scheme and partitions
echo “Creating MBR partition scheme…”
diskutil partitionDisk “$DISK_ID” MBR
“MS-DOS FAT32” “PART1” “${PART1_SIZE}MB”
“Free Space” “PART2” “32MB”
if [ $? -eq 0 ]; then
echo “”
echo “Partitioning completed successfully!”
echo “”
echo “Final disk layout:”
diskutil list “$DISK_ID”
else
echo “Error: Partitioning failed”
exit 1
fi
echo “”
echo “Done. The disk has been partitioned with:”
echo “- Partition 1: FAT32, ${PART1_SIZE}MB”
echo “- Partition 2: Free space, 32MB”