Extending primary partition linux

How to Extend primary partition(/dev/sda1) in linux?

Im having a problem, my primary partition is running out of space. Due to this, I can’t access linux machine remotely (through vncserver). I have another drive (/dev/sdb) having much more free space. I want to shrink space from (/dev/sdb) and extend to (/dev/sda1) partition which is my primary partition and have all linux boot, kernel etc files. What would be best risk free way to do this without losing my data on primary drive(/dev/sda1) ?? fdisk or ‘dd’ command or ‘mount and umount’ ? Any help would be highly appreciated. 🙂

5 Answers 5

You have to use resize2fs command,Which is used to resize your partition.

For more information refer this link.

You can use resize2fs to increase as well as decrease the size of partition. First,you have to decrease the size of /dev/sdb .Then,After increase the size of /dev/sda (Primary partition).

I hope this will helps you.

I’m pretty sure its primary partition is using the maximum it can, and so, won’t be able to resize the underlying filesystem. Thus, a simple resize2fs will fail.

The Risk Free way would be if you can copy(mirror) all your data from /dev/sda1 to some other partition.

After this is done, I would recommend to go with GParted live CD and execute all partition modifying commands from there. This seems to be the most secure way of doing it.

You need a live CD/temp OS to boot on it, resize the new partition to the right size, mount the old and new partitions and copy your files first with

cp -avx /media/originalRootPartition /media/newRootPartition 

Then you should change some references (UUID or partition name) to the new partition in /etc/fstab to match the new partition, and reinstall grub on that new partition :

After prolonged thinking i decided not to extend or shrink any partition as im using amazon EC2 linux instance. They attach 8 GB primary partition by default. After extending instance type(upgrating instance) they gave us another partition instead of extending last one (primary partition). To avoid any future up coming problems, im going to move my all installed softwares like Application server(Glassfish) My SQL server etc to secondary partition. Now the problem is that how can i only move my specific data instead of complete drive data by using ‘dd’ command: e.g dd if=/dev/sda1 of=/dev/sdb

Читайте также:  Настроить виртуал бокс линукс

and set secondary drive(e.g /dev/sdb) for future installation. Like if in future i like to install any software it should by default install to secondary drive instead of primary partition. how i can do this ?

Can you create a new question for that ? There is not enough space in the comment to answer, and editing my question will make it non-valid for your specific question of that page 😉 The answer would be with mount —bind /usr and /var and doing stuff «offline» 😉

Источник

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

Обновлено

Обновлено: 04.04.2023 Опубликовано: 22.06.2017

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

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

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

Мы рассмотрим варианты работы с обычными томами (разделами) и томами LVM. Проверить, какой тип раздела у нас используется можно командой:

Нам интересны варианты part и lvm.

Обычные тома (part)

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

1. С помощью утилиты growpart (без отмонтирования раздела)

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

а) Для систем DEB:

apt install cloud-guest-utils

б) Для систем RPM:

yum install cloud-utils-growpart

Если наш диск имеет разметку GPT, то потребуется установить также утилиту gdisk.

а) Для DEB:

Установка growpart завершена. Идем дальше.

Для расширения раздела /dev/sdb2 вводим команду:

Мы должны увидеть что-то на подобие:

CHANGED: partition=2 start=4096 old: size=20965376 end=20969472 new: size=41938910 end=41943006

2. С помощью утилиты fdisk/parted (требуется отмонтировать раздел)

Данный способ удобнее тем, что не нужно устанавливать дополнительных утилит, но он потребует отмонтирование раздела. Это можно сделать командой:

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

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

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

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

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

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

Читайте также:  Linux check which ports are listening to

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

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

LVM

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

Подробнее о работе с LVM читайте в инструкции Как работать с LVM.

Открываем диск утилитой 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:

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

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

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

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

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

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

Изменение раздела в GParted

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

Уменьшение или увеличение пространства в GParted

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

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

Источник

How to extend primary partition? Linux [duplicate]

My primary partition is running out of space (/dev/sda1). The main partition (/dev/sda) having much more free space. I want to transfer space from (/dev/sda) and extend to (/dev/sda1) partition which is my primary partition and have all linux boot, kernel etc files.

sudo fdisk -l Disk /dev/sda: 204.8 GB, 204803670016 bytes,400007168 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 Device Boot Start End Blocks Id System /dev/sda1 2048 199997439 99997696 Linux 

@炸鱼薯条德里克 if your comment isn’t about requesting a clarification of a technical point, then it is not a comment that needs to be posted. Next time, please keep your unrelated opinions to yourself.

Читайте также:  Linux screen detach attached screen

/dev/sda is not the «main partition», but the whole disk, and /dev/sda1 is part of it. You should simply extend /dev/sda1 with any tool you like (which could mean deleting and then recreating it at the same sector offset/start — 2048, but larger than 48G), and then after you have resized the partition, resize the filesystem residing on it with resize2fs or similar. I suggest you do a dd if=/dev/sda of=saved_mbr count=1 before, so you could restore the original partition if anything goes wrong.

2 Answers 2

There are several things that need doing: re-size partition, then re-size file-system.

To make this easier there is gparted. It is a GUI, it will do both. You can not do it when the file-system is in use, so boot off of a live CD/USB. You can download the gparted OS. A small live OS with just a minimal tool kit, including gparted.

Alternatively

You have a root partition that is large (mine is only 20G).

Add a /home partition. This could fill the rest of the disk, you will not have to reboot. Just create the new partition, and mount it (gparted can do all of this, but you will have to install it first). Next copy you old /home to the new /home . You can use bind mount, to expose the, possibly hidden /home`. (you probably want to logout of any account with data that could be lost, while doing this).

With the command line

It is a long time since I did it this way, as I always have to look it up (I don’t do it enough. I use the command line for most things, but I don’t do this much so use the GUI).

You have to do two things: — resize the partition. — resize the file-system (with the command that you have found).

You should not be using the file-system, when you re-size it. So will need a live CD/USB.

What I would do.

I would add a /home . I always to this, as it makes upgrades to new OS easier (replace OS, keep /home ). You can also make links from other parts of / into /home E.g. /opt → /home/system/opt , /usr/local → /home/system/usr-local …

Источник

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