Deleting All Partitions From the Command Line
How do you delete all partitions on a device from the command line on Linux (specifically Ubuntu)? I tried looking at fdisk, but it presents an interactive prompt. I’m looking for a single command, which I can give a device path (e.g. /dev/sda) and it’ll delete the ext4, linux-swap, and whatever other partitions it finds. Essentially, this would be the same thing as if I were to open GParted, and manually select and delete all partitions. This seems fairly simple, but unfortunately, I haven’t been able to find anything through Google.
9 Answers 9
dd if=/dev/zero of=/dev/sda bs=512 count=1 conv=notrunc
This will not delete the partitions. By deleting the partitions he meant to preserve the MBR and just empty the partition table.
No, this appears to do exactly what I need. I don’t really care if the data is still there. GParted shows that the partitions are gone after running this, and that’s what I wanted.
To be fair, he said delete the partitions, not the partition table or data, so it wasn’t really clear. But I think we knew he just wanted the parts not to register, which makes this the correct answer. To delete the data would be uneccesary. IF you want to zero it, thats a different story, that’s deleting the data too.
The wipefs program lets you easily delete the partition-table signature:
wipefs can erase filesystem, raid or partition-table signatures (magic strings) from the specified device to make the signatures invisible for libblkid.
wipefs does not erase the filesystem itself nor any other data from the device. When used without any options, wipefs lists all visible filesystems and the offsets of their basic signatures.
wipefs calls the BLKRRPART ioctl when it has erased a partition-table signature to inform the kernel about the change.
Quick and Dirty: use gparted to delete the partitions, or if you’re in a hurry:
dd if=/dev/zero of=/dev/[disk device] bs=512 count=1
This will zap the MBR of the drive (Data is still intact).
dd if=/dev/zero of=/dev/[disk device]
to wipe the whole drive (write a single pass of zeros over everything. Not «secure» but usually good enough), or use a «disk shredder» tool for a secure wipe.
Not secure because it’s possible that the disk’s contents could be partially recovered by someone with physical access to it. A secure wipe writes multiple passes of random data over the whole disk.
Use improved non-interactive version of fdisk, which is sfdisk
To erase partition table use this command:
Note: no confirmation will be thrown, the partitions will be deleted instantly and forever!
I think it’s worth making it clear that after running this command there won’t be any confirmation prompts whatsoever, the partition will be deleted instantly.
See man sfdisk , which is a non-interactive variant of fdisk. Other than that, you can delete the whole partition table with dd, as pk wrote.
You should be able to use parted for this aswell, although that may involve some scripting to loop through the partitions.
It may be worth to mention that e.g. parted /dev/mmcblk0 —script mklabel gpt deletes all existing partitions. For me it was parted /dev/mmcblk0 —script mklabel msdos
If we’re talking about MBR-style partitions.
dd if=/dev/zero of=/dev/[disk device] bs=1 count=64 seek=446 conv=notrunc
This standard command copies bytes from a source and writes them to a destination. It’s the simplest flexible tool for this job.
Here, we specify that we’re reading from /dev/zero , which is a special device which emits NUL bytes—zeros.
Here, we specify which device we’re writing to.
dd thinks in terms of blocks. The default block size may be 512 bytes, 1024 bytes or 4096 bytes, depending on your system. However, we need to address things more precisely than that, so we tell dd to use a block size of 1 byte.
Here, we tell dd to write 64 blocks (or bytes, because of our bs=1 parameter), since the primary partition table consists of 4 16-byte partition entries, for a total of 64 bytes.
The primary partition table within the MBR (so, not talking about GPT here) is located 446 bytes in, so we instruct dd to seek 446 bytes in before writing.
Extended partitions are generally created by using a primary partition slot to point at the extended partition table, so if we erase the 4 primary partitions, we effectively wipe the extended partition table as well; the OS won’t be able to find it, so it won’t be able to read and interpret it. (If you want to wipe the extended partition table, you’ll need to know more about the operating system; different operating systems do extended partitions in different ways.)
I wanted to do the same thing (except in Slackware 14.2) but found I could not effect most of the solutions proposed here, with the most elaborate and well-documented solution creating new problems for making replacement partitions. That deleted the partition but some partitioning software apparently found the partition backups automatically.
I found f3probe (http://oss.digirati.com.br/f3) solved the problem of deleting all the partitions, quickly and easily, working with large capacity drives, and created exactly 1 partition spanning the whole drive, which was easy to delete.
It was also easy, from there to create new partitions, in a straight-forward way.
f3probe --destructive --time-ops /dev/sdb # Now we know only 1 partition exists on /dev/sdb # which is /dev/sdb1 # # Unmount that partition umount /dev/sdb1 # # Delete that single partition parted /dev/sdb rm 1 # # Now you can create new partitions # i.e. parted /dev/sdb mkpart primary fat32 1049K 15.8G # # Update /etc/fstab before rebooting.
удаление gpt командой dd
А как корректно удалить (не захватив лишнее) GPT средствами dd?
Почитать в википедии или ещё где-нибудь про структуру GPT и выяснить её полный размер, затем удалять из начала и конца.
Гвозди можно забивать молотком.
А как корректно забить гвоздь гаечным ключом?
Ты хочешь так черезпопчно сделать из gpt-разметки mbr-разметку что ли?
Посмотреть исходный код wipefs.
Разметку GPT конечно смотрел: имеет два «заголовка» — один вначале, другой в конце (дублирует первый, но в обратной последовательности).
512(MBR) + 512(GPT Header) + 128/4*512(Partition Table) итого получается 17408
Первый «заголовок» стало быть удалить легко:
sudo dd if=/dev/zero of=/dev/sdX bs=512 count=34
А для удаления второго заголовка, так понимаю требуется определить размер всего диска, и вот здесь уже начинается кризис идей.
Ограничен в выборе программных средств (делаю это все в образе initramfs, лучше не спрашивайте зачем, это будет уже не по теме).
echo 'x z y w ' | gdisk /dev/sda
. либо sgdisk -Z /dev/sda (или -z, или -o).
делаю это все в образе initramfs
Решил вопрос связкой «fdisk & dd». Отпишу решение с полным тестом удаление/восстановление — возможно кому нибудь пригодится.
Тест провел на следующей флешке:
sudo fdisk -l /dev/sdd Disk /dev/sdd: 7,5 GiB, 8022654976 bytes, 15669248 sectors Units: sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disklabel type: gpt Disk identifier: 15A4B379-6E0D-4222-B39A-A60A61EB48C5 Device Start End Sectors Size Type /dev/sdd1 2048 15669214 15667167 7,5G Linux filesystem sudo gdisk -l /dev/sdd GPT fdisk (gdisk) version 0.8.10 Partition table scan: MBR: protective BSD: not present APM: not present GPT: present
Резервное копирование Primary GPT:
sudo dd if=/dev/sdd of=~/sdd.primary_gpt bs=512 count=34 34+0 записей получено 34+0 записей отправлено скопировано 17408 байт (17 kB), 0,00642818 c, 2,7 MB/c
Резервное копирование Secondary GPT:
_blocksize=$(fdisk -l /dev/sdd | grep Units | awk '') sudo dd if=/dev/sdd of=~/sdd.secondary_gpt skip=$((($(fdisk -l /dev/sdd | grep Disk | awk '')-17408)/$_blocksize)) ibs=$_blocksize 34+0 записей получено 34+0 записей отправлено скопировано 17408 байт (17 kB), 0,00833474 c, 2,1 MB/c
Удаляю Primary GPT, проверяю что получается:
sudo dd if=/dev/zero of=/dev/sdd bs=512 count=34 34+0 записей получено 34+0 записей отправлено скопировано 17408 байт (17 kB), 0,00765282 c, 2,3 MB/c sudo fdisk -l /dev/sdd Disk /dev/sdd: 7,5 GiB, 8022654976 bytes, 15669248 sectors Units: sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes sudo gdisk -l /dev/sdd GPT fdisk (gdisk) version 0.8.10 Caution: invalid main GPT header, but valid backup; regenerating main header from backup! Caution! After loading partitions, the CRC doesn't check out! Warning! Main partition table CRC mismatch! Loaded backup partition table instead of main partition table! Warning! One or more CRCs don't match. You should repair the disk! Partition table scan: MBR: not present BSD: not present APM: not present GPT: damaged Found invalid MBR and corrupt GPT. What do you want to do? (Using the GPT MAY permit recovery of GPT data.) 1 - Use current GPT 2 - Create blank GPT
GPT повредили, но пока не уничтожили.
sudo dd if=/dev/zero of=/dev/sdd seek=$((($(fdisk -l /dev/sdd | grep Disk | awk '')-17408)/$_blocksize)) obs=$_blocksize ibs=17408 count=1 1+0 записей получено 34+0 записей отправлено скопировано 17408 байт (17 kB), 0,0217623 c, 800 kB/c
Проверяю диск на наличие GPT:
sudo fdisk -l /dev/sdd Disk /dev/sdd: 7,5 GiB, 8022654976 bytes, 15669248 sectors Units: sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes sudo gdisk -l /dev/sdd GPT fdisk (gdisk) version 0.8.10 Partition table scan: MBR: not present BSD: not present APM: not present GPT: not present Creating new GPT entries. Disk /dev/sdd: 15669248 sectors, 7.5 GiB Logical sector size: 512 bytes Disk identifier (GUID): 595409AB-6F78-4DD7-A1E9-84993BE23171 Partition table holds up to 128 entries First usable sector is 34, last usable sector is 15669214 Partitions will be aligned on 2048-sector boundaries Total free space is 15669181 sectors (7.5 GiB) Number Start (sector) End (sector) Size Code Name
Пробую восстановить GPT из образов:
sudo dd if=~/sdd.primary_gpt of=/dev/sdd bs=512 count=34 34+0 записей получено 34+0 записей отправлено скопировано 17408 байт (17 kB), 0,00764047 c, 2,3 MB/c sudo dd if=~/sdd.secondary_gpt of=/dev/sdd seek=$((($(fdisk -l /dev/sdd | grep Disk | awk '')-17408)/$_blocksize)) obs=$_blocksize The backup GPT table is corrupt, but the primary appears OK, so that will be used. 34+0 записей получено 34+0 записей отправлено скопировано 17408 байт (17 kB), 0,022258 c, 782 kB/c
Проверяем GPT на наличие и здравие:
sudo fdisk -l /dev/sdd Disk /dev/sdd: 7,5 GiB, 8022654976 bytes, 15669248 sectors Units: sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disklabel type: gpt Disk identifier: 15A4B379-6E0D-4222-B39A-A60A61EB48C5 Device Start End Sectors Size Type /dev/sdd1 2048 15669214 15667167 7,5G Linux filesystem gdisk -l /dev/sdd GPT fdisk (gdisk) version 0.8.10 Partition table scan: MBR: protective BSD: not present APM: not present GPT: present
Все ок! В итоге все благополучно смонтировалось, файлы не пострадали.
How to clear/delete all the partition table from a disk or partition in Linux
Disk /dev/sdb: 17.2 GB, 17179869184 bytes, 33554432 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x1410600c
Device Boot Start End Blocks Id System
/dev/sdb1 2048 4196351 2097152 83 Linux
/dev/sdb2 4196352 10487807 3145728 83 Linux
Now I would like to clear the partition table from this disk
To do so below commands can be used
Check the partition table
Here I have a dos partition table
Clear the partition table
Using the below command you can wipe » dos » partition table
# wipefs -a -t dos -f /dev/sdb
/dev/sdb: 2 bytes were erased at offset 0x000001fe (dos): 55 aa
/dev/sdb: calling ioclt to re-read partition table: Success
If I had a GPT partition table then to clear the same
To clear all the partition tables
You can also delete a partition table using the offset value as shown above
Once the above command returns success, check the partition table using fdisk
Disk /dev/sdb: 17.2 GB, 17179869184 bytes, 33554432 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
As you both my partitions are cleared/deleted.