How to non‑interactive partition → parted /dev/sdX

How to Non-Interactive Partition with Parted /dev/sdX Table of Contents 1. [Introduction](#introduction) 2. [Prerequisites](#prerequisites) 3. [Understanding Parted Non-Interactive Mode](#understanding-parted-non-interactive-mode) 4. [Basic Syntax and Commands](#basic-syntax-and-commands) 5. [Step-by-Step Partitioning Guide](#step-by-step-partitioning-guide) 6. [Practical Examples](#practical-examples) 7. [Advanced Use Cases](#advanced-use-cases) 8. [Automation and Scripting](#automation-and-scripting) 9. [Common Issues and Troubleshooting](#common-issues-and-troubleshooting) 10. [Best Practices](#best-practices) 11. [Conclusion](#conclusion) Introduction The `parted` command is a powerful disk partitioning utility for Linux systems that supports both interactive and non-interactive modes. While the interactive mode provides a user-friendly interface for manual partitioning, non-interactive mode is essential for automation, scripting, and batch operations where human intervention is not desired or possible. Non-interactive partitioning with `parted` allows system administrators, DevOps engineers, and automation scripts to create, modify, and manage disk partitions programmatically. This approach is particularly valuable in scenarios such as server provisioning, container deployments, automated installations, and infrastructure as code implementations. In this comprehensive guide, you'll learn how to effectively use `parted` in non-interactive mode to manage disk partitions on Linux systems. We'll cover everything from basic syntax to advanced scripting techniques, complete with practical examples and troubleshooting guidance. Prerequisites Before diving into non-interactive partitioning with `parted`, ensure you have the following prerequisites: System Requirements - Linux-based operating system (Ubuntu, CentOS, RHEL, Debian, etc.) - Root or sudo privileges for disk operations - The `parted` utility installed on your system - Basic understanding of disk partitioning concepts Installing Parted If `parted` is not installed on your system, install it using your distribution's package manager: Ubuntu/Debian: ```bash sudo apt update sudo apt install parted ``` CentOS/RHEL/Fedora: ```bash sudo yum install parted or for newer versions sudo dnf install parted ``` Safety Considerations - Always backup important data before performing partition operations - Verify the correct device path (`/dev/sdX`) before executing commands - Test commands on non-production systems first - Understand that partitioning operations can result in data loss if performed incorrectly Required Knowledge - Basic Linux command-line operations - Understanding of partition types (primary, extended, logical) - Familiarity with file systems (ext4, xfs, ntfs, etc.) - Knowledge of disk naming conventions in Linux Understanding Parted Non-Interactive Mode Non-interactive mode in `parted` allows you to execute partitioning commands directly from the command line without entering the interactive shell. This mode is controlled by passing commands as arguments to the `parted` command itself. Key Advantages of Non-Interactive Mode 1. Automation-Friendly: Perfect for scripts and automated deployments 2. Batch Operations: Execute multiple commands in sequence 3. Remote Execution: Suitable for SSH-based remote management 4. Error Handling: Easier to capture and handle errors in scripts 5. Reproducibility: Ensures consistent results across multiple systems Command Structure The basic structure for non-interactive `parted` commands is: ```bash parted [options] device [command [parameters]] ``` Where: - `options`: Command-line flags that modify behavior - `device`: The disk device path (e.g., `/dev/sda`, `/dev/nvme0n1`) - `command`: The partitioning operation to perform - `parameters`: Arguments specific to the command Basic Syntax and Commands Essential Parted Commands for Non-Interactive Use 1. Display Partition Information ```bash parted /dev/sda print ``` 2. Create a New Partition Table ```bash parted /dev/sda mklabel gpt parted /dev/sda mklabel msdos ``` 3. Create a New Partition ```bash parted /dev/sda mkpart primary ext4 0% 100% parted /dev/sda mkpart primary 1MiB 1GiB ``` 4. Delete a Partition ```bash parted /dev/sda rm 1 ``` 5. Resize a Partition ```bash parted /dev/sda resizepart 1 2GiB ``` 6. Set Partition Flags ```bash parted /dev/sda set 1 boot on parted /dev/sda set 1 lvm on ``` Common Options - `--script` or `-s`: Suppress interactive prompts and warnings - `--align=TYPE`: Set partition alignment (minimal, optimal, none) - `--version`: Display version information - `--help`: Show help information Step-by-Step Partitioning Guide Let's walk through a complete example of partitioning a disk using non-interactive `parted` commands. Step 1: Identify the Target Disk First, identify the disk you want to partition: ```bash lsblk ``` Example output: ``` NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT sda 8:0 0 20G 0 disk sdb 8:16 0 10G 0 disk sr0 11:0 1 1024M 0 rom ``` Step 2: Check Current Partition Layout Before making changes, examine the current partition structure: ```bash parted /dev/sdb print ``` Step 3: Create a New Partition Table For a fresh disk, create a new partition table. Choose between GPT (recommended for modern systems) or MBR/MSDOS (for legacy compatibility): ```bash For GPT (recommended) parted -s /dev/sdb mklabel gpt For MBR/MSDOS (legacy) parted -s /dev/sdb mklabel msdos ``` Step 4: Create Partitions Create partitions according to your requirements: ```bash Create a 2GB primary partition starting at 1MiB parted -s /dev/sdb mkpart primary ext4 1MiB 2GiB Create a second partition using the remaining space parted -s /dev/sdb mkpart primary ext4 2GiB 100% ``` Step 5: Verify the Partition Layout Confirm that partitions were created correctly: ```bash parted /dev/sdb print ``` Step 6: Set Partition Flags (if needed) Apply any necessary partition flags: ```bash Set boot flag on first partition parted -s /dev/sdb set 1 boot on Set LVM flag on second partition parted -s /dev/sdb set 2 lvm on ``` Practical Examples Example 1: Creating a Basic Boot Drive This example creates a simple boot drive with a boot partition and a root partition: ```bash #!/bin/bash DEVICE="/dev/sdb" Create GPT partition table parted -s $DEVICE mklabel gpt Create EFI System Partition (512MB) parted -s $DEVICE mkpart primary fat32 1MiB 513MiB parted -s $DEVICE set 1 esp on Create root partition (remaining space) parted -s $DEVICE mkpart primary ext4 513MiB 100% Verify the layout parted $DEVICE print ``` Example 2: Setting Up LVM Partitioning This example prepares a disk for LVM (Logical Volume Manager): ```bash #!/bin/bash DEVICE="/dev/sdc" Create GPT partition table parted -s $DEVICE mklabel gpt Create a single partition for LVM parted -s $DEVICE mkpart primary 1MiB 100% Set LVM flag parted -s $DEVICE set 1 lvm on Display results parted $DEVICE print ``` Example 3: Multi-Partition Setup for Server This example creates a typical server partition layout: ```bash #!/bin/bash DEVICE="/dev/sdd" Create GPT partition table parted -s $DEVICE mklabel gpt Boot partition (1GB) parted -s $DEVICE mkpart primary ext4 1MiB 1GiB parted -s $DEVICE set 1 boot on Swap partition (4GB) parted -s $DEVICE mkpart primary linux-swap 1GiB 5GiB Root partition (20GB) parted -s $DEVICE mkpart primary ext4 5GiB 25GiB Home partition (remaining space) parted -s $DEVICE mkpart primary ext4 25GiB 100% Verify the setup parted $DEVICE print ``` Example 4: Resizing Existing Partitions This example demonstrates how to resize partitions non-interactively: ```bash #!/bin/bash DEVICE="/dev/sde" Check current layout echo "Current partition layout:" parted $DEVICE print Resize partition 2 to 10GB parted -s $DEVICE resizepart 2 10GiB Verify the change echo "Updated partition layout:" parted $DEVICE print ``` Advanced Use Cases Working with Different Partition Table Types GPT (GUID Partition Table) GPT is the modern standard that supports: - Disks larger than 2TB - Up to 128 partitions - Better reliability with backup partition tables ```bash parted -s /dev/sdf mklabel gpt parted -s /dev/sdf mkpart primary ext4 1MiB 100% ``` MBR/MSDOS MBR is the legacy standard with limitations: - Maximum disk size of 2TB - Up to 4 primary partitions - Extended partitions for additional logical partitions ```bash parted -s /dev/sdg mklabel msdos parted -s /dev/sdg mkpart primary ext4 1MiB 50% parted -s /dev/sdg mkpart extended 50% 100% parted -s /dev/sdg mkpart logical ext4 50% 100% ``` Handling Different Unit Types Parted supports various unit types for specifying partition sizes: ```bash Using percentages parted -s /dev/sdh mkpart primary ext4 0% 50% Using specific sizes parted -s /dev/sdh mkpart primary ext4 1MiB 1GiB Using sectors parted -s /dev/sdh mkpart primary ext4 2048s 2097152s Using cylinders (legacy) parted -s /dev/sdh mkpart primary ext4 1cyl 100cyl ``` Partition Alignment Proper partition alignment is crucial for optimal performance: ```bash Use optimal alignment (recommended) parted -s --align=optimal /dev/sdi mkpart primary ext4 1MiB 1GiB Use minimal alignment parted -s --align=minimal /dev/sdi mkpart primary ext4 1MiB 1GiB ``` Automation and Scripting Complete Disk Setup Script Here's a comprehensive script that demonstrates best practices for automated disk partitioning: ```bash #!/bin/bash Disk partitioning automation script Usage: ./partition_disk.sh /dev/sdX set -euo pipefail # Exit on error, undefined variables, and pipe failures DEVICE="${1:-}" SCRIPT_NAME=$(basename "$0") Function to display usage information usage() { echo "Usage: $SCRIPT_NAME " echo "Example: $SCRIPT_NAME /dev/sdb" exit 1 } Function to log messages log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" } Function to check if device exists check_device() { if [[ ! -b "$1" ]]; then log "ERROR: Device $1 does not exist or is not a block device" exit 1 fi } Function to confirm operation confirm_operation() { echo "WARNING: This will destroy all data on $DEVICE" read -p "Are you sure you want to continue? (yes/no): " -r if [[ ! $REPLY =~ ^[Yy][Ee][Ss]$ ]]; then log "Operation cancelled by user" exit 0 fi } Main function main() { # Validate input if [[ -z "$DEVICE" ]]; then usage fi # Check if running as root if [[ $EUID -ne 0 ]]; then log "ERROR: This script must be run as root" exit 1 fi # Validate device check_device "$DEVICE" # Confirm operation confirm_operation log "Starting partitioning of $DEVICE" # Unmount any mounted partitions log "Unmounting any mounted partitions on $DEVICE" umount "${DEVICE}"* 2>/dev/null || true # Create GPT partition table log "Creating GPT partition table" parted -s "$DEVICE" mklabel gpt # Create EFI System Partition log "Creating EFI System Partition (512MB)" parted -s "$DEVICE" mkpart primary fat32 1MiB 513MiB parted -s "$DEVICE" set 1 esp on # Create boot partition log "Creating boot partition (1GB)" parted -s "$DEVICE" mkpart primary ext4 513MiB 1537MiB parted -s "$DEVICE" set 2 boot on # Create swap partition log "Creating swap partition (4GB)" parted -s "$DEVICE" mkpart primary linux-swap 1537MiB 5633MiB # Create root partition log "Creating root partition (remaining space)" parted -s "$DEVICE" mkpart primary ext4 5633MiB 100% # Display final partition layout log "Final partition layout:" parted "$DEVICE" print # Wait for device nodes to be created sleep 2 # Format partitions log "Formatting partitions" mkfs.fat -F32 "${DEVICE}1" mkfs.ext4 -F "${DEVICE}2" mkswap "${DEVICE}3" mkfs.ext4 -F "${DEVICE}4" log "Disk partitioning completed successfully" } Execute main function main "$@" ``` Error Handling in Scripts Implement robust error handling in your partitioning scripts: ```bash #!/bin/bash Function to handle errors handle_error() { local exit_code=$? local line_number=$1 echo "Error occurred in script at line $line_number: exit code $exit_code" exit $exit_code } Set error trap trap 'handle_error $LINENO' ERR Your partitioning commands here DEVICE="/dev/sdb" Check if parted command succeeded if ! parted -s "$DEVICE" mklabel gpt; then echo "Failed to create partition table" exit 1 fi echo "Partition table created successfully" ``` Common Issues and Troubleshooting Issue 1: Device Busy Error Problem: Getting "device busy" error when trying to partition. Solution: ```bash Check what's using the device lsof /dev/sdb fuser -v /dev/sdb Unmount all partitions umount /dev/sdb* 2>/dev/null || true Disable swap if it's a swap partition swapoff /dev/sdb1 2>/dev/null || true Stop any LVM volumes vgchange -an 2>/dev/null || true ``` Issue 2: Alignment Warnings Problem: Receiving partition alignment warnings. Solution: ```bash Use proper alignment parted -s --align=optimal /dev/sdb mkpart primary ext4 1MiB 1GiB Check alignment parted /dev/sdb align-check optimal 1 ``` Issue 3: Permission Denied Problem: Cannot access device due to permissions. Solution: ```bash Check device permissions ls -la /dev/sdb Run with sudo sudo parted -s /dev/sdb print Add user to disk group (requires logout/login) sudo usermod -a -G disk $USER ``` Issue 4: Partition Table Type Mismatch Problem: Trying to create incompatible partition types. Solution: ```bash Check current partition table type parted /dev/sdb print Convert to appropriate type if needed parted -s /dev/sdb mklabel gpt # for GPT parted -s /dev/sdb mklabel msdos # for MBR ``` Issue 5: Size Calculation Errors Problem: Partitions not created with expected sizes. Solution: ```bash Use specific units parted -s /dev/sdb mkpart primary ext4 1MiB 1024MiB Use percentages for relative sizing parted -s /dev/sdb mkpart primary ext4 0% 50% Check actual sizes after creation parted /dev/sdb print ``` Debugging Commands Use these commands to troubleshoot partitioning issues: ```bash Show detailed device information parted /dev/sdb print all Show partition alignment parted /dev/sdb align-check optimal 1 Display disk usage df -h Show block devices lsblk -f Check for errors in system logs dmesg | tail -20 journalctl -xe | grep -i parted ``` Best Practices 1. Always Use the Script Flag Use the `-s` or `--script` flag to suppress interactive prompts: ```bash parted -s /dev/sdb mklabel gpt ``` 2. Implement Proper Error Handling Always check command return codes in scripts: ```bash if ! parted -s /dev/sdb mklabel gpt; then echo "Failed to create partition table" exit 1 fi ``` 3. Use Appropriate Alignment Always use optimal alignment for best performance: ```bash parted -s --align=optimal /dev/sdb mkpart primary ext4 1MiB 1GiB ``` 4. Verify Operations Always verify the results of partitioning operations: ```bash parted /dev/sdb print lsblk /dev/sdb ``` 5. Backup Critical Data Before performing any partitioning operations: ```bash Create a backup of the partition table sfdisk -d /dev/sdb > partition_backup.txt Create a full disk image (for small disks) dd if=/dev/sdb of=disk_backup.img bs=1M ``` 6. Use Descriptive Partition Labels When creating partitions, use meaningful names: ```bash parted -s /dev/sdb mkpart boot ext4 1MiB 1GiB parted -s /dev/sdb mkpart root ext4 1GiB 20GiB parted -s /dev/sdb mkpart home ext4 20GiB 100% ``` 7. Test on Non-Production Systems Always test partitioning scripts on non-production systems first: ```bash Use loop devices for testing dd if=/dev/zero of=test_disk.img bs=1M count=1024 losetup /dev/loop0 test_disk.img parted -s /dev/loop0 mklabel gpt ... test your commands ... losetup -d /dev/loop0 ``` 8. Document Your Partition Schemes Maintain documentation of your partitioning schemes: ```bash #!/bin/bash Partition scheme for web servers /dev/sdb1: 512MB EFI System Partition /dev/sdb2: 1GB boot partition /dev/sdb3: 4GB swap partition /dev/sdb4: 20GB root partition /dev/sdb5: Remaining space for /var/www ``` 9. Use Consistent Sizing Units Stick to consistent units throughout your scripts: ```bash Use MiB for consistency parted -s /dev/sdb mkpart primary ext4 1MiB 513MiB parted -s /dev/sdb mkpart primary ext4 513MiB 1537MiB ``` 10. Implement Logging Add comprehensive logging to your scripts: ```bash log_file="/var/log/disk_partitioning.log" exec 1> >(tee -a "$log_file") exec 2> >(tee -a "$log_file" >&2) echo "[$(date)] Starting disk partitioning" ``` Conclusion Non-interactive partitioning with `parted` is an essential skill for system administrators and DevOps professionals working with Linux systems. This comprehensive guide has covered everything from basic syntax to advanced automation techniques, providing you with the knowledge and tools needed to effectively manage disk partitions programmatically. Key takeaways from this guide include: 1. Understanding the fundamentals of non-interactive `parted` usage and its advantages over interactive mode 2. Mastering essential commands for creating, modifying, and managing partitions 3. Implementing best practices for safe and reliable partitioning operations 4. Developing automation scripts that handle errors gracefully and provide detailed logging 5. Troubleshooting common issues that may arise during partitioning operations Remember that disk partitioning operations can be destructive, so always: - Backup important data before making changes - Test scripts on non-production systems - Verify operations after completion - Use proper error handling in automated scripts By following the practices and examples outlined in this guide, you'll be able to confidently implement non-interactive disk partitioning solutions that are reliable, maintainable, and suitable for production environments. Whether you're provisioning new servers, setting up automated deployment pipelines, or managing infrastructure at scale, the techniques covered in this guide will help you effectively leverage `parted` for all your disk partitioning needs. For further learning, consider exploring related topics such as LVM management, filesystem creation and management, and advanced storage technologies like software RAID and disk encryption.