Fdisk linux extend partition

2 easy methods to extend/shrink resize primary partition in Linux

Table of Contents

Related Searches: How to resize primary partition in Linux. How to extend non lvm root partition. How to change size of partition in Linux using parted and fdisk without destroying data. Steps to expand partition in RHEL/CentOS 7 and 8 Linux. Perform Disk Management in CentOS. How to use unallocated space to change size of partition in a disk in Linux. How to resize root partition not on LVM in Linux. Step by step guide to resize primary partition. How to expand partition with examples in Linux. centos disk management. rhel 7 extend non lvm root partition. centos 7 resize root partition. Steps to resize primary partition to extend non lvm root partition in linux. how to add unallocated disk space to a partition in Linux. centos shrink or extend non lvm root partition. add space to partition. fdisk extend partition. resize boot partition. extend non lvm root partition in linux. change size of partition.how to expand partition. centos resize primary partition. rhel change size of partition.

Earlier I had shared steps to create a file system and check file system type in Linux . Now in this article I will share the steps to resize primary partition, here we will extend non lvm root partition. With LVM it is far more easier and less riskier to change size of partition in an volume group in Linux .

  • This article covers steps to resize primary partition (non-lvm) which can be dangerous and can leave your Linux system in an unusable broken state. It is important that you backup your content before you attempt to change size of partition.
  • You can change size of partition (non-lvm) only on the last partition on the storage device with unallocated space. If the respective partition is not the last partition then the only way to expand partition is to backup your data , rebuild the disk and partitions, then restore the data. No tool such as gparted, parted or fdisk can help you change size of partition in such case.
  • You must have some unallocated space or free space available in the concerned device to be able to expand partition. In some of the virtual environment you have an option to change the storage device size but on physical node if there is no enough unallocated space then resize primary partition (extend non lvm root partition) is not possible
  • This article assumes you’re using either a GPT partition table, or an msdos partition table using primary partition types to extend non lvm root partition.

Lab Environment to resize primary partition (RHEL/CentOS 7/8) in Linux

I have performed resize primary partition operation on Virtual Machine running on Oracle VirtualBox installed on Linux server . My VM is running with CentOS 8 but I have also verified these steps on RHEL/CentOS 7 and RHEL 8 Linux.

Here my VM is installed on /dev/sda device where /dev/sda1 is boot partition, /dev/sda2 is root while /dev/sda3 is for swap.. Additionally I have left some unallocated free space in /dev/sda for the demonstration of this article to extend non lvm root partition.

Method 1: Change size of partition using parted CLI utility

You can either use gparted (GUI utility) or parted (CLI utility) to change size of partition in Linux. Here we plan to resize primary partition which in our case is /dev/sda.

List available partitions

To list the available partitions in /dev/sda we will execute below command

As I mentioned in the disclaimer section, you can change size of partition only on the last partition of the device but here root partition ( /dev/sda2 ) is not the last one instead swap ( /dev/sda3 ) is my last partition. So to expand root partition I must delete swap device to be able to to use unallocated space and extend non lvm root partition. After deleting swap, root partition will become the last partition on /dev/sda after which we can resize primary partition.

Disable swap partition

Currently I have around 1GB reserved for swap partition

I will turn off my swap (disable swap partition) and use this space to extend non lvm root partition in Linux

Verify the swap partition space, as you see not it is 0

Update /etc/fstab to make sure swap partition is not mounted at boot up stage.

Читайте также:  Mac os sierra как обновить систему

Delete swap and expand partition

Now to resize primary partition /dev/sda2 and expand partition to a new value we must first delete swap partition using parted utility. As we need root partition to be the last partition of /dev/sda before we expand partition.

But our root partition is showing the same size as earlier i.e.

To complete the steps to resize non lvm root partition, execute resizefs to expand partition and refresh the changes

Re-verify the new size of root partition to make sure our steps to extend non lvm root partition was successful.

Re-create swap partition

Now we must create Swap partition which we deleted earlier in this article. We will again use parted utility to create swap partition

Now with parted we only created a partition with file system type as swap. Use mkswap to turn this partition into swap.

Next we must update /etc/fstab with the UUID of our new swap partition. To get the new UUID of swap partition

Update this UUID in /etc/fstab as shown below

Finally turn on the new swap partition

Verify the new swap partition

Now you can reboot your Linux server to make sure everything is OK and resize primary partition was successful.

Method 2: Change size of partition using fdisk utility

Similar to parted command, you can also use fdisk utility to resize primary partition and extend non lvm root partition.

List available partitions

Before we resize primary partition, let us list the available partitions

Now as you see my existing root partition /dev/sda2 size is

10G . Here we will expand partition with +1GB using unallocated disk space from /dev/sda .

Delete swap partition

Currently my swap partition is enabled and is the last partition of /dev/sda . So we must first delete swap partition here before we change size of partition as we need root to be the last partition in /dev/sda

So we will turn off the swap partition before we disable it

Now it is time to use fdisk utility to resize partition

Part 1 — Resize root partition

We will continue with the steps to extend non lvm root partition in the same fdisk session. Note down the start sector of the root partition before you expand partition.

Create swap partition

After we resize primary partition, in the same fdisk session we will also create a new swap partition which we had deleted initially with new start and end sector

Update the kernel regarding the recent changes we did to change size of partition

But our swap partition is still shown as 0

Now let us complete our steps to create swap partition using mkswap

Next update /etc/fstab with the UUID for your new swap partition. You can use blkid to get the UUID

Update the same in /etc/fstab as shown below

Now you can turn on the swap partition

Verify the same using free command

Part 2 — Resize root partition

If not done already in above steps, once you exit fdisk utility, update the kernel regarding the recent changes we did to change size of partition

We are not done with resize primary partition, as df command still shows old partition size for root partition

Execute resize2fs to expand partition on /dev/sda2 with the new changes

Now you can verify the new size of root partition

Lastly I hope the steps from the article to resize primary partition and extend non lvm root partition on RHEL/CentOS 7/8 Linux was helpful. So, let me know your suggestions and feedback using the comment section.

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Источник

Расширение диска или раздела Linux

В инструкции рассмотрены сценарии расширения дискового пространства разделов в Linux без потери информации.

Принцип увеличения диска:

  1. Расширение раздела.
  2. Изменение размера файловой системы.

В зависимости от типа раздела и файловой системы, действия различаются.

Любая работа с диском несет риск потери информации. Перед началом работ убедитесь в наличие резервных копий ценных данных.

Шаг 1. Расширение раздела

Обычные тома

Допустим, есть диск /dev/sdb и раздел /dev/sdb2, который нужно увеличить.

Сначала необходимо отмонтировать раздел:

В случае работы с корневой директорией, отмонтировать ее не получиться. В таком случае необходимо загрузить компьютер с LiveCD.

Подключаемся утилитой fdisk к /dev/sdb:

Если мы работаем с разделом более чем 2Тб, используем утилиту parted.

Смотрим номера разделов:

Удаляем раздел (не переживайте — все данные сохраняются):

* в моем примере, раздел для удаления на второй позиции.

Создаем новый раздел:

Номер раздела — 2:

На запрос начального и конечного секторов просто нажимаем Enter.

Если раздел был загрузочный, добавляем соответствующий флаг:

Еще раз проверяем, что получилось:

Читайте также:  Отмена автоматической установки драйверов windows 10

LVM-тома расширяются на лету, даже для корневых разделов. В данном примере, работаем с /dev/sda.

Открываем диск утилитой fdisk:

* напомню, что при работе с диском 2Тб и более, следует использовать утилиту parted.

Создаем еще один раздел:

Номер раздела оставляем тот, который предлагает система (просто нажимаем Enter).

Первый и последний сектора также оставляем по умолчанию для использования всего дискового пространства (еще два раза Enter).

Задаем тип раздела:

Выбираем номер раздела (в моем примере создавался раздел 3):

Командой L можно посмотреть список всех типов, но нас интересует конкретный — LVM (8e):

Проинформируем систему, что в таблице разделов произошли изменения:

Создаем физический том из нового раздела:

Смотрим наши Volume Group и для нужного добавляем созданный том:

vgextend vg_centos /dev/sda3

* в моем примере группа томов LVM называется vg_centos

Смотрим LVM-разделы и расширяем пространства для нужного:

lvextend -l +100%FREE /dev/vg_centos/lv_root

* данная команда расширяем LVM-раздел /dev/vg_centos/lv_root, используя все свободное пространство (100%FREE).

Шаг 2. Изменение размера для файловой системы

После того, как на предыдущем шаге мы расширили раздел, система по-прежнему будет видеть старый по объему диск. Чтобы это исправить, необходимо выполнить команду по изменению размера файловой системы. В зависимости от последней, команды различаются.

Посмотреть файловую систему:

ext2/ext3/ext4:

XFS:

Reiserfs:

* обратите внимание, что в данных примерах используются различные устройства.

Если раздел был отмонтирован, монтируем его, например:

mount /dev/sda2 /mnt

Проверяем, что настройки применились:

Увеличение разделов с Gparted

Если работы выполняются на системе с графическим интерфейсом или есть возможность перезагрузить сервер и загрузиться с LiveCD, можно воспользоваться простым средством — утилитой Gparted, которая позволяем менять размер разделов мышкой.

Запускаем утилиту — выбираем диск, с которым будем работать — кликаем правой кнопкой по разделу, который хотим увеличить и выбираем Resize/Move:

В открывшемся окне с помощью мышки или форм меняем размер раздела:

Нажимаем кнопку Resize/Move.

Проверяем изменения в окне программы и сохраняем настройки кнопкой «Apply All Operations»:

Источник

Fdisk linux extend partition

This section shows you how to actually partition your hard drive with the fdisk utility. Linux allows only 4 primary partitions. You can have a much larger number of logical partitions by sub-dividing one of the primary partitions. Only one of the primary partitions can be sub-divided.

Four primary partitions (see Section 5.2 )

Mixed primary and logical partitions (see Section 5.3 )

fdisk is started by typing (as root) fdisk device at the command prompt. device might be something like /dev/hda or /dev/sda (see Section 2.1.1 ). The basic fdisk commands you need are:

p print the partition table

n create a new partition

d delete a partition

q quit without saving changes

w write the new partition table and exit

Changes you make to the partition table do not take effect until you issue the write (w) command. Here is a sample partition table:

Disk /dev/hdb: 64 heads, 63 sectors, 621 cylinders Units = cylinders of 4032 * 512 bytes Device Boot Start End Blocks Id System /dev/hdb1 * 1 184 370912+ 83 Linux /dev/hdb2 185 368 370944 83 Linux /dev/hdb3 369 552 370944 83 Linux /dev/hdb4 553 621 139104 82 Linux swap

The first line shows the geometry of your hard drive. It may not be physically accurate, but you can accept it as though it were. The hard drive in this example is made of 32 double-sided platters with one head on each side (probably not true). Each platter has 621 concentric tracks. A 3-dimensional track (the same track on all disks) is called a cylinder. Each track is divided into 63 sectors. Each sector contains 512 bytes of data. Therefore the block size in the partition table is 64 heads * 63 sectors * 512 bytes er. divided by 1024. (See 4 for discussion on problems with this calculation.) The start and end values are cylinders.

which indicates that I am using the second drive on my IDE controller. (See Section 2.1 .) When I print the (empty) partition table, I just get configuration information.

Command (m for help): p Disk /dev/hdb: 64 heads, 63 sectors, 621 cylinders Units = cylinders of 4032 * 512 bytes

I knew that I had a 1.2Gb drive, but now I really know: 64 * 63 * 512 * 621 = 1281982464 bytes. I decide to reserve 128Mb of that space for swap, leaving 1153982464. If I use one of my primary partitions for swap, that means I have three left for ext2 partitions. Divided equally, that makes for 384Mb per partition. Now I get to work.

Command (m for help): n Command action e extended p primary partition (1-4) p Partition number (1-4): 1 First cylinder (1-621, default 1): Using default value 1 Last cylinder or +size or +sizeM or +sizeK (1-621, default 621): +384M

Next, I set up the partition I want to use for swap:

Command (m for help): n Command action e extended p primary partition (1-4) p Partition number (1-4): 2 First cylinder (197-621, default 197): Using default value 197 Last cylinder or +size or +sizeM or +sizeK (197-621, default 621): +128M

Now the partition table looks like this:

Device Boot Start End Blocks Id System /dev/hdb1 1 196 395104 83 Linux /dev/hdb2 197 262 133056 83 Linux

I set up the remaining two partitions the same way I did the first. Finally, I make the first partition bootable:

Command (m for help): a Partition number (1-4): 1

And I make the second partition of type swap:

Command (m for help): t Partition number (1-4): 2 Hex code (type L to list codes): 82 Changed system type of partition 2 to 82 (Linux swap) Command (m for help): p

Disk /dev/hdb: 64 heads, 63 sectors, 621 cylinders Units = cylinders of 4032 * 512 bytes Device Boot Start End Blocks Id System /dev/hdb1 * 1 196 395104+ 83 Linux /dev/hdb2 197 262 133056 82 Linux swap /dev/hdb3 263 458 395136 83 Linux /dev/hdb4 459 621 328608 83 Linux

Finally, I issue the write command (w) to write the table on the disk.

The overview: create one use one of the primary partitions to house all the extra partitions. Then create logical partitions within it. Create the other primary partitions before or after creating the logical partitions.

which indicates that I am using the first drive on my SCSI chain. (See Section 2.1 .)

First I figure out how many partitions I want. I know my drive has a 183Gb capacity and I want 26Gb partitions (because I happen to have back-up tapes that are about that size).

so I will need 7 partitions. Even though fdisk accepts partition sizes expressed in Mb and Kb, I decide to calculate the number of cylinders that will end up in each partition because fdisk reports start and stop points in cylinders. I see when I enter fdisk that I have 22800 cylinders.

> The number of cylinders for this disk is set to 22800. There is > nothing wrong with that, but this is larger than 1024, and could in > certain setups cause problems with: 1) software that runs at boot > time (e.g., LILO) 2) booting and partitioning software from other > OSs (e.g., DOS FDISK, OS/2 FDISK)

So, 22800 total cylinders divided by seven partitions is 3258 cylinders. Each partition will be about 3258 cylinders long. I ignore the warning msg because this is not my boot drive (Section 4 ).

Since I have 4 primary partitions, 3 of them can be 3258 long. The extended partition will have to be (4 * 3258), or 13032, cylinders long in order to contain the 4 logical partitions.

I enter the following commands to set up the first of the 3 primary partitions (stuff I type is bold ):

Command (m for help): n Command action e extended p primary partition (1-4) p Partition number (1-4): 1 First cylinder (1-22800, default 1): Using default value 1 Last cylinder or +size or +sizeM or +sizeK (1-22800, default 22800): 3258

The last partition is the extended partition:

Partition number (1-4): 4 First cylinder (9775-22800, default 9775): Using default value 9775 Last cylinder or +size or +sizeM or +sizeK (9775-22800, default 22800): Using default value 22800

The result, when I issue the print table command is:

/dev/sda1 1 3258 26169853+ 83 Linux /dev/sda2 3259 6516 26169885 83 Linux /dev/sda3 6517 9774 26169885 83 Linux /dev/sda4 9775 22800 104631345 5 Extended

Next I segment the extended partition into 4 logical partitions, starting with the first logical partition, into 3258-cylinder segments. The logical partitions automatically start from /dev/sda5.

Command (m for help): n First cylinder (9775-22800, default 9775): Using default value 9775 Last cylinder or +size or +sizeM or +sizeK (9775-22800, default 22800): 13032

Device Boot Start End Blocks Id System /dev/sda1 1 3258 26169853+ 83 Linux /dev/sda2 3259 6516 26169885 83 Linux /dev/sda3 6517 9774 26169885 83 Linux /dev/sda4 9775 22800 104631345 5 Extended /dev/sda5 9775 13032 26169853+ 83 Linux /dev/sda6 13033 16290 26169853+ 83 Linux /dev/sda7 16291 19584 26459023+ 83 Linux /dev/sda8 19585 22800 25832488+ 83 Linux

Finally, I issue the write command (w) to write the table on the disk. To make the partitions usable, I will have to format (Section 10.1 ) each partition and then mount (Section 10.3 ) it.

I’d like to submit my partition layout, because it works well with any distribution of Linux (even big RPM based ones). I have one hard drive that . is 10 gigs, exactly. Windows can’t see above 9.3 gigs of it, but Linux can see it all, and use it all. It also has much more than 1024 cylenders.

Table 7. Partition layout example

Partition Mount point Size
/dev/hda1 /boot (15 megs)
/dev/hda2 windows 98 partition (2 gigs)
/dev/hda3 extended (N/A)
/dev/hda5 swap space (64 megs)
/dev/hda6 /tmp (50 megs)
/dev/hda7 / (150 megs)
/dev/hda8 /usr (1.5 gigs)
/dev/hda9 /home (rest of drive)

I also noticed that you don’t have any REAL examples of partition tables, and for newbies I HIGHLY suggest putting quite a few up. I’m freshly out of the newbie stage, and partitioning was what messed me up the most.

Источник

Читайте также:  Windows password key инструкция
Оцените статью