Linux remove all partitions

Linux: How to delete a partition with fdisk command

Q . My system comes with pre installed Linux and XP. Now I would like to delete a partition. How do I delete a partition?

A . Hard disks can be divided into one or more logical disks called partitions. This division is described in the partition table found in sector 0 of the disk.

You need to use fdisk command. It is a menu driven program for creation and manipulation of partition tables. However this program needs the device name (hard disk name) to manipulate partitions. Usually you use following names
/dev/hda
/dev/hdb
/dev/sda
/dev/sdb

So,
=> /dev/hd[a-h] for IDE disks
=> /dev/sd[a-p] for SCSI disks
=> /dev/ed[a-d] for ESDI disks
=> /dev/xd[ab] for XT disks.

A device name refers to the entire hard disk. For more information see Linux partition naming convention and IDE drive mappings.

Before typing any one of the following command(s) make sure you have the backup of important data.

First, get a listing of your current partition scheme, type the following command:
# fdisk -l.
Output:

From above output I have two hard disks:
=> /dev/hda – 20 GB
=> /dev/hdb – 80 GB

Let us assume that you want to remove a partition from /dev/hdb disk. Type the following command:
# fdisk /dev/hdb
Output:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Now type p command to list partition:
Command (m for help): p
Output:

Now let us say you want to delete /dev/hdb3 (3rd partition). Type the d command to delete a partition:
Command (m for help): d
Partition number (1-4): 3

It will prompt you for the partition number. Type 3:

Verify that partition deleted:
Command (m for help): p

Now save the changes and exit to shell prompt. Type the w command:
Command (m for help): w

Reboot the system.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Как удалить раздел в 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:

Если раздел сейчас смонтирован в системе, то удалить его вы не сможете. На это указывает ключ возле диска. Сначала необходимо его размонтировать. Для этого откройте контекстное меню и выберите Отмонтировать:

Читайте также:  Sign in from firefox on windows

Далее можно удалить раздел. Для этого в том же контекстном меню выберите Удалить. Теперь этот пункт будет активным:

Раздел удалён в интерфейсе программы, но изменения ещё не применены к системе. Для того чтобы их применить кликните по зелёной галочке или откройте меню Правка и выберите Применить все изменения:

Далее применение изменений надо подтвердить. Если не возникло никаких ошибок, дальше пойдёт процесс удаления раздела, а потом вы сможете пользоваться появившемся свободным местом по своему усмотрению:

Теперь вы знаете удалить разделы на диске 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 несколькими способами. Как видите, есть простые способы, есть более сложные, но во всём можно разобраться. А какой программой пользуетесь вы для удаления разделов? Напишите в комментариях!

Источник

How to Delete Partitions in Linux [Beginner’s Guide]

Managing partitions is serious business, especially when you have to remove them. I find myself doing this frequently, especially after using thumb drives as live disks and Linux installers because they create several partitions that I won’t need afterwards.

In this tutorial, I will show you how to remove partitions in Linux using both command line and GUI tools.

You delete the partition, you lose your data. Whenever you are playing with partitions, make sure backup your data. A slight typo or slip of finger could prove costly. Don’t say we didn’t warn you!

Читайте также:  Как перезагрузить компьютер при установке windows

Remove disk partition using GParted [GUI Method]

As a desktop Linux user, you probably will be more comfortable and perhaps safer with a GUI-based tool.

There are several tools that let you manage partitions on Linux. Depending on your distribution you will have one or even more such tool already installed on your system.

For this tutorial, I am going to use GParted. It is a popular open source tool and it’s very easy and intuitive to use.

The first step is installing GParted if it isn’t already in your system. You should be able to find it in the software center of your distribution.

Alternatively, you can use your distribution’s package manager for installing it. In Debian and Ubuntu-based Linux distributions, you can use the apt install command:

Once installed, let’s open GParted. Since you are dealing with disk partitions, you’ll be required to have root access. It will ask for authentication and once it opens you should see a window like this one:

On the right-upper corner you can select the disk and in the lower screen the partition you want to remove.

Next, select the option Delete from the Partition menu:

The process is incomplete until you rewrite the partition table. This is a safety measure and it gives you the option to review the changes before confirming it.

To do this just click on the Apply All Operations button located in the toolbar and then Apply when asked for confirmation.

After hitting Apply, you will see a progress bar and a results message saying that all the operations were successful. You can close the message and the main window and consider your partition completely deleted from our disk.

Now that you are aware of the GUI method, let’s move on to the command line.

Delete partitions using fdisk command

Almost every Linux distribution comes with fdisk by default and we are going to use this tool today. The first thing you need to know is what device is assigned to the disk with the partitions you want to remove. To do that, type the following in the terminal:

This will print all the drives and partitions in our system as well as the assigned devices. You need to have root access in order for it work.

In this example, I will work with a USB drive that contains two partitions as shown below:

The device assigned in the system is /sdb and it has two partitions, sdb1 and sdb2. Now that you identified which device contains the partitions, you can start working on it by using fdisk and the path to the device:

This will start fdisk in command mode. You can always press m to see a list of options.

Next, type p and press Enter to view the partition information and confirm that you are using the right device. If the wrong device is in use you can use the q command to exit fdisk and start the procedure again.

Now enter d to delete a partition and it will immediately ask for the partition number, that corresponds to the number listed in the Device column, which in this case are numbers 1 and 2 (as can be seen in the screen capture below) but can and will vary according to the current partition table.

Let’s remove the second partition by typing 2 and pressing Enter . You should see a message saying “Partition 2 has been deleted“, but actually, it hasn’t been removed yet. fdisk needs one more step to rewrite the partition table and apply the changes. Safety net, you see.

You need to type w and press Enter to make the changes permanent. No confirmation is asked.

After this, you should receive some feedback like the one here:

Now, use sudo fdisk —list /dev/sdb to view the current partition table of the device and you can see that the second partition is completely gone. You are done removing your partition using the terminal and fdisk command. Success!

Читайте также:  Урок информатики операционная система windows

Wrapping up

And so I end this tutorial on how to remove partitions in Linux using both the terminal and GUI tools. Remember, stay always on the safe side, backup your files before manipulating your partitions and double check that you are using the right device. Deleting a partition will delete everything in it with little to no chance of recovering it.

Like what you read? Please share it with others.

About Chris Patrick Carias Stas

Chris is an old-school techie, Linux and FOSS advocate, avid reader and a teacher by vocation. He is usually found deep into books, playing TTRPGs or having fun with his many pets.

fdisk do not support GPT tables, for old tables this article is just fine but for GPT fdisk is useless

Not true anymore. fdisk handles also gpt partitions quite well nowadays.

How do you resize an existing partition to ‘expand’ and fill up the space left after deleting a partition on your disk?

Hi, I am struggling with the same issue, decrease size of one partition and increase size of another one.

I have done some trials on my VB installation
– first you have to decrease a large partition , to make some free space, You can use Gparted or Disk and you will have to use a life CD because you cannot resize a partition that is mounted.
– once you have a free unallocated part, you have to arrange this such its is adjacent to the partition you want to increase.
– again ,with a life CD using Gparted you can try to increase the size of selected partition with the amount max of what is free.

success, and don’t forget first to make a BACKUP!

Could we ask ItsFoss to make some more of these partitions articles, with how to expand an partition, how to upgrade a new fresh Ubuntu version without loosing your data in /home, etc. etc.

Before you begin, BACK UP the partition you will be working on.
Execute GParted.
The unallocated space must be directly adjacent to either the left or the right boundary of the partition you wish to enlarge.
You right click on the partition you want to expand.
From the drop-down menu, click on RESIZE/MOVE.
On the succeeding screen, either drag the boundary of your target partition to the right or left into the unallocated space, or reduce the Free Space Preceding or Free Space Following window to Zero MiB (or any other number you wish). The number in the New Size box will change as your are changing the Preceding and Following boxes. That shows what the new size of the target partion will be.
Click on Resize.
Click on Apply and get a cup of coffee. Depending on the amount of space you are adding, the process can take anywhere from 5 minutes to 30 minutes and more.

If the unallocated space IS NOT adjacent to the partition you want to enlarge, you will have to Move partitions until the unallocated space IS next to the desired partition.
To Move a partition, You right click on the partition you want to move.
From the drop-down menu, click on RESIZE/MOVE.
If you want to move the partition left, on the succeeding screen, copy the number from Free Space Preceding box into the Free Space Following box, leaving the number in New Size box the same.
To move the partition to the right, copy the Free Space Following number into the Free Space Preceding box, again leaving New Size the same.
Then you can proceed with expanding your target partition into the resulting unallocated space.
Moving a partition takes even more time than Resizing it.

I hope the above is clear enough to help you.

Источник

Оцените статью