- 2 easy methods to extend/shrink resize primary partition in Linux
- Lab Environment to resize primary partition (RHEL/CentOS 7/8) in Linux
- Method 1: Change size of partition using parted CLI utility
- List available partitions
- Disable swap partition
- Delete swap and expand partition
- Re-create swap partition
- Method 2: Change size of partition using fdisk utility
- List available partitions
- Delete swap partition
- Part 1 — Resize root partition
- Create swap partition
- Part 2 — Resize root partition
- Related Posts
- Расширение диска или раздела Linux
- Шаг 1. Расширение раздела
- Обычные тома
- Шаг 2. Изменение размера для файловой системы
- Увеличение разделов с Gparted
- 8 Linux ‘Parted’ Commands to Create, Resize and Rescue Disk Partitions
- How to Install Parted on Linux
- 1. Check Parted Version
- 2. List Linux Disk Partitions
- 3. List or Switch to Different Disk
- 4. Create Primary or Logical Partition in Linux
- 5. Resize Linux Disk Partition
- 6. Delete Linux Partition
- 7. Rescue Linux Disk Partition
- 8 Change Linux Partition Flag
- Conclusion
- If You Appreciate What We Do Here On TecMint, You Should Consider:
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.
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.
Related Posts
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. Расширение раздела
Обычные тома
Допустим, есть диск /dev/sdb и раздел /dev/sdb2, который нужно увеличить.
Сначала необходимо отмонтировать раздел:
В случае работы с корневой директорией, отмонтировать ее не получиться. В таком случае необходимо загрузить компьютер с LiveCD.
Подключаемся утилитой fdisk к /dev/sdb:
Если мы работаем с разделом более чем 2Тб, используем утилиту parted.
Смотрим номера разделов:
Удаляем раздел (не переживайте — все данные сохраняются):
* в моем примере, раздел для удаления на второй позиции.
Создаем новый раздел:
Номер раздела — 2:
На запрос начального и конечного секторов просто нажимаем Enter.
Если раздел был загрузочный, добавляем соответствующий флаг:
Еще раз проверяем, что получилось:
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»:
Источник
8 Linux ‘Parted’ Commands to Create, Resize and Rescue Disk Partitions
Parted is a famous command line tool that allows you to easily manage hard disk partitions. It can help you add, delete, shrink and extend disk partitions along with the file systems located on them. Parted has gone a long way from when it first came out. Some of it’s functions have been removed, others have been added.
Parted Command to Manage Linux Disk Partitions
In this tutorial you will learn the basics of parted and we will show you some practical examples. If you don’t have any previous experience with parted, please be aware that parted writes the changes immediately to your disk, so be careful if you try to modify your disk partitions.
If you plan on testing parted, the better option would be to simply use a virtual machine or old computer/laptop without any valuable information on it. To make modifications on a disk partition it must not be in use. If you need to work on primary partition, you may boot into rescue mode.
Note: You will need to have root access to the machine you will be working on in order to use parted.
How to Install Parted on Linux
On many Linux distributions, parted comes pre-installed. If it is not included in your distro, you can install it with:
Once you have make sure that parted is installed, you can proceed further to check out some real world examples of parted command in the rest of this article.
1. Check Parted Version
Run the following command, you see message similar to the one shown on the image below. Don’t worry if your parted version is different. Unless specified otherwise, parted will use your primary drive, which in most cases will be /dev/sda .
Check Parted Command Version
If you want to exit parted, simply type:
2. List Linux Disk Partitions
Now that parted is started, let’s list the partitions of the selected hard disk. As mentioned earlier, parted chooses your first drive by default. To see the disk partitions run print .
Check Linux Partitions
When running print , it will also display the hard disk information and model. Here is example from a real hard disk (not virtual as shown on the image above) :
In the example above, you can see the disk model, capacity sector size and partition table.
3. List or Switch to Different Disk
If you have more than one hard disk, you can easily switch between disks, by using the “ select ” command. In the example below, I will switch from /dev/sda to /dev/sdb which is a secondary drive on my system.
To easily switch between disks you can use:
Select Different Disk
Change «X» with the letter of the disk to which you wish to switch.
4. Create Primary or Logical Partition in Linux
Parted can be used to create primary and logical disk partitions. In this example, I will show you how to create primary partition, but the steps are the same for logical partitions.
To create new partition, parted uses “ mkpart “. You can give it additional parameters like «primary» or «logical» depending on the partition type that you wish to create.
Before you start creating partitions, it’s important to make sure that you are using (you have selected) the right disk.
Start by using print:
Show Current Linux Disk
As shown on the above image, we are using a virtual drive of 34 GB. First we will give the new disk a label and then create a partition and set a file system on it.
Now the first step is to give the new disk a label name with:
Now create the new partition with mkpart . The listed units are in megabytes (MB). We will create a 10 GB partition starting from 1 to 10000:
Create Primary or Logical Linux Partitions
Next, exit parted with «quit» command. We will format our new partition in ext4 file system using mkfs . To make this happen run the following command:
Note: It’s important to select the right disk and partition when executing the above command!
Now let’s verify our results, by printing the partition table on our secondary disk. Under file system column, you should see ext4 or the file system type that you have decided to use for your partition:
Verify Disk Partition Filesystem
5. Resize Linux Disk Partition
Parted includes multiple useful functions and one of them is «resizepart» . As you have probably figured this out by now, «resizepart» helps you resize a partition.
In the example below, you will see how to resize an existing partition. For the purpose of this example, we will be using the earlier created partition.
First you will need to know the number of the partition that you will be resizing. This can be easily found by using «print» :
Find Linux Partition Number
In our example, the partition number is «1» . Now run the resizepart command:
You will be asked for the number of the partition that you will resize. Enter it’s number. After that, you will be asked to set the new ending point for this partition. Remember that by default the units are in MB. In our example, we have set the new partition size to 15 GB:
Now verify the results with «print» :
Verify Linux Resize Partition
6. Delete Linux Partition
The next thing you will learn is how to delete a partition from your hard drive. To do this, you will need to use the «rm» command within parted. To delete a disk partition you will need to know it’s number.
As mentioned earlier, you can easily obtain this number by using «print» . In our example, we will delete the partition with number 1 from our secondary drive /dev/sdb1 :
Verify the results by printing the partitions table:
Delete a Linux Partition
7. Rescue Linux Disk Partition
Parted supports a “ rescue» utility that helps you recover a lost partition between a starting and ending point. If a partition is found within that range, it will attempt to restore it.
Here is an example:
8 Change Linux Partition Flag
Using parted, you can change the state of a flag for disk partitions. The supported flags are:
The states can be either «on» or «off» . To change a flag simply run «set» command within parted:
The above command sets lba flag to on for second partition. Verify the results with print :
Change Partition Flag
Conclusion
Parted is a useful and powerful utility that can help you manage your disk partitions in Linux systems. As always, when working with disk partitions you need to be extra careful. It is strongly recommend to go through parted man pages to learn how you can customize it’s output and find more information about its capabilities.
If you have any questions or comments, please do not hesitate to use the comment section below.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник