How to Delete Partition in Linux
Linux users create partitions to organize their data in an efficient manner. As easy as they are created, Linux partitions can be deleted to reformat a storage device and regain storage space.
In this step-by-step tutorial, you will learn how to delete a partition on a Linux system.
- A system running Linux
- A user account with sudo or root privileges
- Access to a terminal window / command line (Activities > Search > Terminal)
- The fdisk command-line utility
Delete a Partition in Linux
Deleting a partition in Linux requires selecting the disk containing the partition and using the fdisk command-line utility to delete it.
Follow the steps outlined in the sections below to delete partitions in Linux.
Note: The fdisk command-line utility is a text-based partition table manipulator. It is used for partitioning and repartitioning storage devices.
Step 1: List Partition Scheme
Before deleting a partition, run the following command to list the partition scheme.
In our case, the terminal prints out information about two disks: /dev/sda and /dev/sdb . Disk /dev/sda contains the operating system, therefore its partitions should not be deleted.
On the /dev/sdb disk, there is a /dev/sdb1 partition which we are about to delete.
Note: The number 1 in /dev/sdb1 indicates the partition number. Make a note of the number of the partition you intend to delete.
Step 2: Select the Disk
Select the disk that contains the partition you intend to delete.
Common disk names on Linux include:
Step 3: Delete Partitions
Before deleting a partition, back up your data. All data is automatically deleted when a partition is deleted.
To delete partition, run the d command in the fdisk command-line utility.
The partition is automatically selected if there are no other partitions on the disk. If the disk contains multiple partitions, select a partition by typing its number.
The terminal prints out a message confirming that the partition is deleted.
Note: If you wish to delete multiple partitions, repeat this step as many times as necessary.
Step 4: Verify Partition Deletion
Reload the partition table to verify that the partition has been deleted. To do so, run the p command.
The terminal prints out the partition structure of the disk selected in Step 2.
Step 5: Save Changes and Quit
Run the w command to write and save changes made to the disk.
After following the instructions in this tutorial, you should have learned how to delete a partition in Linux.
If you want to learn more about partition manipulation, we recommend reading our tutorial on creating partitions in Linux or if you are running NTFS partitions, check out our article on how to mount NTFS partitions in Linux.
How to Delete a Partition in Linux?
There are 2 ways you can delete a partition in Linux:
- Using the fdisk command-line utility
- Using the Gparted GUI tool
Delete a Partition Using the fdisk Command-line Tool
The fdisk command-line utility is a tool that ships with every Linux distribution and comes in handy when you want to create or delete hard disk partitions.
Usually, partitions take naming conventions, as shown below:
For IDE drives: /dev/hdx e.g /dev/hda , /dev/hdb, /dev/hdc
For ISCI disks: /dev/sdx e.g /dev/sda, /dev/sdb, /dev/sdc
Before deleting a partition, it is imperative that you back up all the files and directories since they are going to be wiped out.
In my system, I have attached a removable drive, /dev/sdb, with 2 partitions. To display the partitions, I will execute the fdisk command as shown. If you are using a regular user, ensure to use the sudo command since fdisk requires elevated privileges.
Alternatively, you can use the lsblk command to get a better visual as follows:
The drive has 2 partitions: /dev/sdb1 and /dev/sdb2. I’m going to delete the second partition, which is /dev/sdb2.
To get started, invoke the fdisk command-line tool:
Next, you will be prompted to enter a command to proceed. Type ‘P’ to print the existing partitions on the drive.
Command (m for help): p
To remove the partition, type the letter ‘d’ which stands for delete and
Command (m for help): d
Thereafter, provide the partition number. In my case, I will type 2 and press “ENTER” since this is the partition that I intend to delete.
Partition number (1, 2, default 2): 2
You will be notified that the partition has been removed or deleted. You can cross-check by printing out the partitions again by typing the p command.
At the bottom of the snippet below, only /dev/sdb1 is listed.
To save changes to the disk, type w for write and press “q” to quit the fdisk shell.
As before, confirm the existing partitions using the fdisk tool.
Delete a Partition Using the GParted Tool
Gparted is a powerful graphical tool that allows you to view, resize, create and delete your partitions. It is open-source and absolutely free and can be installed as follows:
For Debian/Ubuntu Distributions
For Debian/Ubuntu distros, run the command below to install Gparted:
For CentOs
For CentOS-based systems, first, install EPEL. Then install Gparted using the yum package manager:
For Arch
For Arch and Arch-based distros, invoke:
To launch Gparted, run the following command on the terminal:
Also, you can use the application manager to search and launch the GUI utility.
Provide your password to authenticate and hit “ENTER”.
Once authenticated, Gparted will present the partitions on the main hard drive on which Linux is installed, in my case, it’s /dev/sda.
Since the partition to be deleted is located on the removable drive, which is not listed, we will switch to that hard drive.
To do so, we will go to Gparted > Devices > /dev/sdb
We now have the partitions of the second hard drive listed, as shown below:
To delete the second partition (/dev/sdb2), we will unmount it first. So, right-click and select “unmount”.
Next, right-click on the /dev/sdb2 partition, and select the “delete” option, which ultimately removes or deletes the partition.
Immediately, you will realize that the partition is labeled “Unallocated” and at the bottom left corner of the Gparted window, you will notice an alert informing you of a pending operation. The reason you are getting this is that we have not saved the changes to the disk.
Click on the checkmark, as indicated, to apply the changes made.
When prompted whether to proceed with the pending operations, click on “Apply”.
Ultimately, the writing process will conclude and the changes saved. Click on the “close” button.
Conclusion
We have covered two ways that you can employ to delete a logical partition in Linux: fdisk utility and Gparted GUI tool. If you find this informative, send us a like and share this guide.
About the author
Karim Buzdar
Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. He blogs at LinuxWays.
How to remove a partition on a hard disk?
When I was basically new to Linux (and I still quite am), I got a nice computer from my university, featuring a SSD (250 Gb) and a 2Tb hard disk.
I decided to use only Ubuntu, but I made the installation being distracted and I did it on the 2Tb hard disk, while I wanted it on the SSD. So now I have two partitions, one on the SSD and the other one on this 2Tb hard disk.
I need to free the 2Tb hard disk; I tried with GParted, but I don’t get how to use it, plus it seems like this partition is locked.
How do I get rid of this useless partition? Do I just need to delete the linux-swap in order to be able to use the hard disk?
here what I see in Gparted
6 Answers 6
You can try to use fdisk from the command line. In your case, if you want to delete partition on /dev/sdb just type:
Then once fdisk is opened you can type "d" to delete and then select the partition(s) you want to delete. After you removed the partition(s) don’t forget to write the changes (type "w").
One advice, do not do that if you didn’t reinstalled your OS on /dev/sda (your SSD) or you won’t be able to boot the computer then.
You must unmount a partition before you can delete it.
Currently /dev/sdb1 is mounted at /media/elisa/d91c. .
If you right-click on the partition’s entry in GParted, there should be an option «Unmount» in the context menu. Click it.
After that, you can modify or delete the partition as you wish.
First Let’s remove some confusions
Every hard drive needs one or more partitions to be useful. Partitions are created when you create a filesystem on it. Most used partitions scheme is MBR. In MBR, you can have only 4 partitions in a disk. These are called Primary partition. If you need more than 4 partitions, You can make one of the 4 as Extended partition. This extended partition works as a container and it turn can hold more than 1 partitions. These partitions are called Logical partitions
In your GParted image, the first partition (bigger one) is a primary partition. And the Swap partition is a logical partition inside an Extended partition
Answer
If I understood your question correctly, You later installed Ubuntu on SSD, but you still have that 2TB disk with two partitions. 1 with 30 GB of Data and another is a swap (inside an Extended partition).
If you’re trying to free the space of linux-swap thinking It’s useless, Then I’d say not to delete that partition. Because Linux Swap is helpful for hibernating and 31 GB won’t hurt much considering your disk size.
If you really want to remove the swap
If you really want to remove this swap, click on the swap partition, right click, select Swapoff. Then again select it, right click and use Delete to remove the partition.
You can then see that there is still a partition (extended partition) with empty space. Select that space, right click and select Delete again. This will clear the Extended partition
Now, select the partition with Data (bigger one), right click -> Resize/Move and in the new Resize Window, move the right slider to far right to fill the partition. Finally click Resize/Move button.
Как удалить раздел в Linux
Если вы работаете с дисками в Linux, то у вас время от времени возникает необходимость создавать таблицы разделов, создавать и форматировать новые разделы, а также удалять разделы. Это может понадобится для установки ещё одной системы, или просто перераспределения свободного места между разделами.
Удалить раздел в Linux можно как в графическом интерфейсе, так и в командной строке. Причем, в командной строке для этого есть несколько утилит. Есть да утилита с псевдографическим интерфейсом. В этой статье мы рассмотрим как выполняется удаление разделов Linux разными способами.
Как удалить разделы на диске Linux
1. Графический интерфейс
В графическом интерфейсе чаще всего для управления дисками и разделами используется программа Gparted. Обычно она уже предустановлена в большинстве дистрибутивов. Если же в вашем дистрибутиве её нет, то программу достаточно просто установить. Для этого в Ubuntu или Debian выполните такую команду:
sudo apt install gparted
Для Fedora команда будет выглядеть вот так:
sudo dnf install gparted
В Arch Linux тоже будет отличаться только пакетный менеджер:
sudo pacman -S gparted
Запустить программу можно из главного меню:
Далее в правом верхнем углу программы выберите диск, на котором вы хотите удалить раздел. В данном случае будет использоваться /dev/sdb:
Если раздел сейчас смонтирован в системе, то удалить его вы не сможете. На это указывает ключ возле диска. Сначала необходимо его размонтировать. Для этого откройте контекстное меню и выберите Отмонтировать:
Далее можно удалить раздел. Для этого в том же контекстном меню выберите Удалить. Теперь этот пункт будет активным:
Раздел удалён в интерфейсе программы, но изменения ещё не применены к системе. Для того чтобы их применить кликните по зелёной галочке или откройте меню Правка и выберите Применить все изменения:
Далее применение изменений надо подтвердить. Если не возникло никаких ошибок, дальше пойдёт процесс удаления раздела, а потом вы сможете пользоваться появившемся свободным местом по своему усмотрению:
Теперь вы знаете удалить разделы на диске Linux в графическом интерфейсе.
2. Псевдографический интерфейс
Если вам нужно удалить раздел Linux в терминале, но у вас нет доступа к графическому интерфейсу и вы не хотите пользоваться утилитами командной строки, можно воспользоваться утилитой с псевдографическим интерфейсом — cfdisk. Если она ещё не установлена в вашей системе её можно установить так:
sudo apt install cfdisk
Для других дистрибутивов будет отличаться только пакетный менеджер. Перед запуском утилиты надо определиться на каком диске нужно удалять раздел. Для этого можно воспользоваться командой lsblk:
Например, можно удалить тот же /dev/sdb1. Обратите внимание, что если этот раздел диска примонтирован к системе, то его сначала надо отмонтировать. Для этого выполните:
sudo umount /dev/sdb1
Теперь запустите утилиту и передайте ей в параметре имя диска, на котором расположен этот раздел. Команду надо выполнять от имени суперпользователя:
sudo cfdisk /dev/sdb
В окне утилита отобразит список доступных разделов на выбранном диске:
В низу окна программы есть кнопки, которыми вы можете пользоваться для удаления и создания разделов. Перемещаться по ним можно с помощью кнопок со стрелками вправо и влево, а по разделам диска — стрелками вверх и вниз. Выберите нужный раздел, а затем кнопку Удалить и нажмите Enter:
Утилита сообщает, что раздел удалён, но как и в случае с Gparted изменения надо записать на диск, для этого нажмите кнопку Запись:
Затем введите слово yes, для того чтобы подтвердить изменения:
Теперь вы можете использовать полученное свободное пространство. Для того чтобы закрыть программу используйте кнопку Выход. Благодаря cfdisk удалить разделы жесткого диска linux в терминале не так уже и сложно.
3. Командная строка
Если два предыдущих варианта вам не подходят, можете воспользоваться утилитой fdisk. У неё нет никакого интерфейса и вам придется делать всё вручную. Сначала посмотрите список дисков:
Далее можно запускать программу. Программе необходимо передать путь к диску (не разделу), на котором надо удалить раздел и запустить её надо от имени суперпользователя. Например:
sudo fdisk /dev/sdb
Утилита работает в интерактивном режиме и имеет свой интерпретатор команд. Для вывода доступных команд нажмите m и Enter:
Для того чтобы посмотреть список разделов на выбранном диске выполните команду p:
Для удаления раздела необходимо выполнить команду d. Обратите внимание на номера разделов в списке после sdb. Команда спросит номер раздела, который вы хотите удалить и именно этот номер надо указать. Например 1:
Все изменения выполнены только в памяти программы. Для того чтобы записать их на диск и удалить разделы fdisk linux необходимо использовать команду w:
После этого можно пользоваться свободным пространством. Более подробно об утилите fdisk можно почитать в этой статье.
Выводы
В этой небольшой статье мы разобрали как удалить раздел в Linux несколькими способами. Как видите, есть простые способы, есть более сложные, но во всём можно разобраться. А какой программой пользуетесь вы для удаления разделов? Напишите в комментариях!
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.