Linux partition with parted

Parted (Русский)

GNU Parted — это программа для создания и редактирования таблиц разделов. GParted это GUI для неё.

Contents

Установка

Установите parted пакет. Для графического интерфейса, установить gparted пакет, графический интерфейс для parted.

Использование

Parted имеет два режима: коммандная строка и интерактивный. Parted всегда должен начинаться с:

где device это жёсткий диск, который нужно отредактировать (например /dev/sda ). Если не указать device аргумент, parted может предположить какое устройство вы хотите.

Режим командной строки

В режиме командной строки, он принимает одну или более команд. Например:

Интерактивный режим

Интерактивный режим упрощает процесс разбиения и уменьшает ненужное повторение с помощью автоматического применения всех команд разбиения на указанное устройство.

Чтобы начать работу с устройством, выполните:

Вы заметите что префикс командной строки ( # ) отличается от (parted) : это также означает, что новая строка не является командой, которую нужно вводить вручную при запуске команд в примерах.

Чтобы увидеть список доступных команд, введите:

Когда закончите, или если хотите сделать таблицу разделов или схему для другого устройства, выйдите из parted с помощью:

После выхода, префикс командной строки измениться обратно на # .

Если вы не указываете параметр команде, Parted подскажет вам его. Например:

Округление

Поскольку многие системы разделов имеют сложные ограничения, Parted обычно будет делать что-то немного другое, чем вы просили. (Например, создание раздела начиная с 10.352Mb, не с 10.4Mb) Если рассчитанные значения слишком сильно отличаются, Parted попросит у вас подтверждения. Если вы точно знаете, что хотите, или точно видите, что делает Parted, это может помоч указать конечные точки разделов в секторах. (с помощью «s» суффикса) и указать «unit s» команду, чтобы конечные точки раздела отображались в секторах.

В parted-2.4, когда вы указываете начало и/или конец значения с использованием двоичных единиц IEC, например “MiB”, “GiB”, “TiB”, и т.д., parted обрабатывает эти значения как точные и равны тому же числу, указанному в байтах (то есть с суффиксом «B»), в том, что он не дает “полезный” диапозон. Сравните это с запросом на запуск раздела “4GB”, который может фактически разрешиться в некотором секторе до 500MB до или после этого момента. Таким образом, при создании раздела лучше указывать единицы байтов (“B”), сектора (“s”), или двоичные блоки IEC, такие как “MiB”, но не “MB”, “GB”, и т.д.

Разбиение

Создание новой таблицы разделов

Вам нужно (пере)создать таблицу разделов устройства, если она никогда ранее не разбивалась, или когда вы хотите изменить тип этих таблиц разделов. Пересоздание таблицы разделов устройства также будет полезно когда схема разделов требует реконструкции с нуля.

Откройте каждое устройство, таблица разделов которого должна быть (пере)создана с помощью:

Затем создайте новую GUID Partition Table, используйте следующую команду:

Чтобы создать новую Главную Загрузочную Запись/MS-DOS таблицу разделов, используйте:

Схемы разделов

Вы можете выбрать количество и размер разделов, на которые должны быть разделены устройства, и какие каталоги будут использоваться для монтирования разделов в установленной системе (также известной как mount points). Смотрите Разбиение#Схема разметки для необходимых разделов.

Следующая команда будет использоваться для создания разделов:

  • part-type-or-part-label интерпретируется по-разному в зависимости от таблицы разделов:
    • MBR: параметр интерпретируется как part-type , который может быть primary , extended или logical .
    • GPT: параметр интерпретируется как part-label , который устанавливает PARTLABEL атрибут раздела. Метка раздела должна быть установлена всегда, так как mkpart не разрешает создавать разделы без метки.
    • start это начало раздела от начала устройства. Он состоит из числа, за которым следует unit, например 1MiB означает начало с 1 MiB.
    • end конец раздела от начала устройства (not из start значения). Он имеет тот же синтаксис, что и start , например 100% означает конец в конце устройства (использовать все оставшееся пространство).

    Следующая команда будет использоваться для отметки раздела, содержащего /boot директорию как загрузочную:

    • partition — номер раздела, который должен быть отмечен (смотрите вывод команды print ).
    • esp это назначения для boot на GPT. [1]

    This article or section needs expansion.

    UEFI/GPT примеры

    В каждом случае специальный загрузочный EFI system partition (Русский) is required.

    При создании нового системного раздела EFI используйте следующие команды (рекомендуемый размер — не менее 260 MiB):

    Оставшаяся схема разделов полностью зависит от вас. Для другого раздела, использующего 100% оставшегося пространства

    Для / (20 GiB) и /home (все оставшееся пространство) разделов:

    Для / (20 GiB), swap (4 GiB), и /home (все оставшееся пространство) разделов:

    BIOS/MBR примеры

    Для минимального одного основного раздела, использующего все доступное дисковое пространство, будет использоваться следующая команда:

    В следующем случае, 20 GiB / будет создан раздел, за которым последует /home раздел, используя все оставшееся пространство:

    В последнем примере, /boot (100 MiB), / (20 GiB), swap (4 GiB), and /home (все оставшееся пространство) разделы будут созданы:

    Изменения размера разделов

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

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

    Чтобы увеличить размер (в интерактивном режиме parted):

    Где number — номер раздела, который вы увеличиваете, и end — новый конец раздела (который должен быть больше старого).

    Затем чтобы увеличить (ext2/3/4) файловую систему на разделах:

    Или увеличить Btrfs файловую систему:

    Где sdaX обозначает раздел, который вы увеличиваете, и [size] — новый размер раздела. Примечание; [size] опциональный, по умолчанию: заполнить оставшееся место на разделе.

    Сжатие разделов

    Чтобы сжать ext2/3/4 файловую систему на разделе:

    Чтобы сжать Btrfs файловую систему:

    Где sdaX обозначает раздел, который вы сжимаете, и size — новый размер раздела.

    Затем сожмите раздел (в интерактивном режиме parted):

    Где number — номер раздела, который вы сжимаете, и end — новый конец раздела (который должен быть меньше старого конца).

    Когда закончите, используйте resizepart команду из util-linux сообщающая ядру о новом размере:

    Где device — устройство, на котором находиться раздел, number — номер раздела и size — новый размер раздела, в 512-байт секторах.

    Предупреждения

    Parted will always warn you before doing something that is potentially dangerous, unless the command is one of those that is inherently dangerous (e.g. rm, mklabel and mkpart).

    Выравнивание

    При создании раздела, parted может предупредить о неправильном выравнивании раздела, но не поможет с правильным выравнивание. Например:

    Предупреждение означает, что начало раздела не выровнено. Введите «Ignore» что проигнорировать, вывести таблицу разделов по секторам, чтобы увидеть, где она начинается, и удалить/пересоздать раздел с начала сектора округляя до увеличения степени до 2, пока предупреждение не прекратится. В качестве одного из примеров, на флешке с секторами 512B, Parted найдёт разделы начинающиеся на секторах которые кратны 2048, что соответствует выравниванию в 1 MiB.

    Если вы хотите parted может попытаться рассчитать для вас правильное выравнивание, укажите начальную позицию как 0% вместо некоторого конкретного значения. Чтобы сделать один большой ext4 раздел, ваша команда должна выглядить так:

    Советы и приемы

    Dual boot с Windows XP

    Если вы имеете Windows XP разделы которые вы хотите переместить с диска на диск, а также ваш загрузочный раздел, вы можете легко сделать это с помощью GParted и оставаться на Windows счастливым, просто удалив следующий ключ реестра ДО перемещения раздела:

    Ссылка на источник здесь.

    Проверка выравнивания

    На существующем размеченном диске, вы можите использовать parted чтобы проверить выравнивание разделов на диске. Например, проверить выравнивание раздела 1 на /dev/sda :

    Устранение проблем

    Раздел FAT32 после изменения размера, не распознается в Windows

    По состоянию на декабрь 2018 г, в parted была ошибка, patched in git 2016-04-15, но всё ещё присутствовала в Arch Linux (и ряду других дистрибутивов) из-за того, что не было официального релиза parted с 2014-07-28.[3] Эта проблема была решена в upstream после выпуска новой разделенной версии в 2019-08-12, и решена в Arch с 3.3-1 выпуска parted в 2019-10-11.[4]

    Для старых сборок, однострочный обходной путь был упомянут в отчете об ошибке, но в отчете также указывалось, что он не работал должным образом для всех. [5][6]

    Следует отметить, что этот вопрос во многом не коснулся gparted, поскольку проект включил патч в свою сборку от gparted версии 0.26.0-1 (выпущенной в 2016-04-29).[7]

    gparted на Wayland вызывает ошибку «cannot open display: :0»

    Данная проблема возникает потому, что xwayland получает отказ в доступе от gparted запущенном от имени root . разработчики gparted реализовали [8] небольшой обходной путь, который временно добавляет root в список пользователей, которым разрешёно подключаться xwayland пока приложение запущено.

    Источник

    Creating and managing partitions in Linux with parted

    More Linux resources

    So you need to manage a storage device? Well, if you are a Linux administrator, then you are in luck. As it turns out, there are a ton of different tools and command suites that you can use to accomplish this. Today we are going to look at the parted command suite. GNU parted (PARTition EDitor) was created by Andrew Clausen and Lennert Buytenhek. It runs at the command line, or with a graphical interface, if that’s more your speed. We are going to focus on the command line variant here. Let’s look at some of the functionality parted offers.

    The parted utility

    Parted allows you to add, shrink, extend, and remove partitions from storage disks on your system. Be sure of what you are doing when making changes to partitions. I recommend that you explore the tool on a virtual machine that contains no important data. You will also need root access to the system. I am using parted on Red Hat Enterprise Linux 8 for this example. Parted comes pre-installed in this particular distro, but if you need to install it on a different Linux flavor, there is plenty of information online. For now, let’s take a look at the basic operations with which you will want to be familiar.

    Listing partitions with parted

    The first thing that you want to do anytime that you need to make changes to your disk is to find out what partitions you already have. Displaying existing partitions allows you to make informed decisions moving forward and helps you nail down the partition names will need for future commands. Run the parted command to start parted in interactive mode and list partitions. It will default to your first listed drive. You will then use the print command to display disk information.

    Creating new partitions with parted

    Now that you can see what partitions are active on the system, you are going to add a new partition to /dev/sdc . You can see in the output above that there is no partition table for this partition, so add one by using the mklabel command. Then use mkpart to add the new partition. You are creating a new primary partition using the ext4 architecture. For demonstration purposes, I chose to create a 50 MB partition.

    Modifying existing partitions with parted

    Now that you have created the new partition at 50 MB, you can resize it to 100 MB, and then shrink it back to the original 50 MB. First, note the partition number. You can find this information by using the print command. You are then going to use the resizepart command to make the modifications.

    You can see in the above output that I resized partition number one from 50 MB to 100 MB. You can then verify the changes with the print command. You can now resize it back down to 50 MB. Keep in mind that shrinking a partition can cause data loss.

    Removing partitions with parted

    Now, let’s look at how to remove the partition you created at /dev/sdc1 by using the rm command inside of the parted suite. Again, you will need the partition number, which is found in the print output.

    NOTE: Be sure that you have all of the information correct here, there are no safeguards or are you sure? questions asked. When you run the rm command, it will delete the partition number you give it.

    Parted is another great option for manipulating hard disks in Linux, and is about as easy to use as any tool I’ve seen! From creation, deletion, shrinking, extending, etc, there is so much functionality offered. I highly recommend that you take the time to learn parted , and if you have the chance, consider using it to accomplish your next partitioning job!

    [ Want to test your sysadmin skills? Take a skills assessment today. ]

    Источник

    Parted

    GNU Parted is a program for creating and manipulating partition tables. GParted is a GUI frontend.

    Contents

    Installation

    Install the parted package. For a graphical interface, install the gparted package, the graphical frontend to parted.

    Usage

    Parted has two modes: command line and interactive. Parted should always be started with:

    where device is the hard disk device to edit (for example /dev/sda ). If you omit the device argument, parted will attempt to guess which device you want.

    Command line mode

    In command line mode, this is followed by one or more commands. For example:

    Interactive mode

    Interactive mode simplifies the partitioning process and reduces unnecessary repetition by automatically applying all partitioning commands to the specified device.

    In order to start operating on a device, execute:

    You will notice that the command-line prompt changes from a hash ( # ) to (parted) : this also means that the new prompt is not a command to be manually entered when running the commands in the examples.

    To see a list of the available commands, enter:

    When finished, or if wishing to implement a partition table or scheme for another device, exit from parted with:

    After exiting, the command-line prompt will change back to # .

    If you do not give a parameter to a command, Parted will prompt you for it. For example:

    Rounding

    Since many partitioning systems have complicated constraints, Parted will usually do something slightly different to what you asked. (For example, create a partition starting at 10.352Mb, not 10.4Mb) If the calculated values differ too much, Parted will ask you for confirmation. If you know exactly what you want, or to see exactly what Parted is doing, it helps to specify partition endpoints in sectors (with the «s» suffix) and give the «unit s» command so that the partition endpoints are displayed in sectors.

    As of parted-2.4, when you specify start and/or end values using IEC binary units like “MiB”, “GiB”, “TiB”, etc., parted treats those values as exact, and equivalent to the same number specified in bytes (i.e., with the “B” suffix), in that it provides no “helpful” range of sloppiness. Contrast that with a partition start request of “4GB”, which may actually resolve to some sector up to 500MB before or after that point. Thus, when creating a partition, you should prefer to specify units of bytes (“B”), sectors (“s”), or IEC binary units like “MiB”, but not “MB”, “GB”, etc.

    Partitioning

    Create new partition table

    You need to (re)create the partition table of a device when it has never been partitioned before, or when you want to change the type of its partition table. Recreating the partition table of a device is also useful when the partition scheme needs to be restructured from scratch.

    Open each device whose partition table must be (re)created with:

    To then create a new GUID Partition Table, use the following command:

    To create a new Master Boot Record/MS-DOS partition table instead, use:

    Partition schemes

    You can decide the number and size of the partitions the devices should be split into, and which directories will be used to mount the partitions in the installed system (also known as mount points). See Partitioning#Partition scheme for the required partitions.

    The following command will be used to create partitions:

    • part-type-or-part-label is interpreted differently based on the partition table:
      • MBR: the parameter is interpreted as part-type , which can be one of primary , extended or logical .
      • GPT: the parameter is interpreted as part-label , which sets the PARTLABEL attribute of the partition. The partition label always has to be set, since mkpart does not allow to create partitions with empty label.
      • start is the beginning of the partition from the start of the device. It consists of a number followed by a unit, for example 1MiB means start at 1 MiB.
      • end is the end of the partition from the start of the device (not from the start value). It has the same syntax as start , for example 100% means end at the end of the device (use all the remaining space).

      The following command will be used to flag the partition that contains the /boot directory as bootable:

      • partition is the number of the partition to be flagged (see the output of the print command).
      • esp is an alias for boot on GPT. [1]

      This article or section needs expansion.

      UEFI/GPT examples

      In every instance, a special bootable EFI system partition is required.

      If creating a new EFI system partition, use the following commands (the recommended size is at least 260 MiB):

      The remaining partition scheme is entirely up to you. For one other partition using 100% of remaining space:

      For separate / (20 GiB) and /home (all remaining space) partitions:

      And for separate / (20 GiB), swap (4 GiB), and /home (all remaining space) partitions:

      BIOS/MBR examples

      For a minimum single primary partition using all available disk space, the following command would be used:

      In the following instance, a 20 GiB / partition will be created, followed by a /home partition using all the remaining space:

      In the final example below, separate /boot (100 MiB), / (20 GiB), swap (4 GiB), and /home (all remaining space) partitions will be created:

      Resizing partitions

      If you are growing a partition, you have to first resize the partition and then resize the filesystem on it, while for shrinking the filesystem must be resized before the partition to avoid data loss.

      Growing partitions

      To grow a partition (in parted interactive mode):

      Where number is the number of the partition you are growing, and end is the new end of the partition (which needs to be larger than the old end).

      Then, to grow the (ext2/3/4) filesystem on the partition:

      Or to grow a Btrfs filesystem:

      Where sdaX stands for the partition you are growing, and [size] is the new size of the partition. Note that [size] is optional, leave it off to fill the remaining space on the partition.

      Shrinking partitions

      To shrink an ext2/3/4 filesystem on the partition:

      To shrink a Btrfs filesystem:

      Where sdaX stands for the partition you are shrinking, and size is the new size of the partition.

      Then shrink the partition (in parted interactive mode):

      Where number is the number of the partition you are shrinking, and end is the new end of the partition (which needs to be smaller than the old end).

      When done, use the resizepart command from util-linux to tell the kernel about the new size:

      Where device is the device that holds the partition, number is the number of the partition and size is the new size of the partition, in 512-byte sectors.

      Warnings

      Parted will always warn you before doing something that is potentially dangerous, unless the command is one of those that is inherently dangerous (e.g. rm, mklabel and mkpart).

      Alignment

      When creating a partition, parted might warn about improper partition alignment but does not hint about proper alignment. For example:

      The warning means the partition start is not aligned. Enter «Ignore» to go ahead anyway, print the partition table in sectors to see where it starts, and remove/recreate the partition with the start sector rounded up to increasing powers of 2 until the warning stops. As one example, on a flash drive with 512B sectors, Parted wanted partitions to start on sectors that were a multiple of 2048, which is 1 MiB alignment.

      If you want parted to attempt to calculate the correct alignment for you, specify the start position as 0% instead of some concrete value. To make one large ext4 partition, your command would look like this:

      Tips and tricks

      Dual booting with Windows XP

      If you have a Windows XP partition that you would like to move from drive-to-drive that also happens to be your boot partition, you can do so easily with GParted and keep Windows happy simply by deleting the following registry key PRIOR to the partition move:

      Reference to this little gem here.

      Check alignment

      On an already partitioned disk, you can use parted to verify the alignment of a partition on a device. For instance, to verify alignment of partition 1 on /dev/sda :

      Troubleshooting

      Resized FAT32 partition then unrecognized on Windows

      As of December 2018, there was a bug in parted which had been patched in git on 2016-04-15, but was still present in Arch Linux (and a number of other distros) due to there not having been an official release of parted since 2014-07-28.[3] This was resolved upstream once a new parted release was pushed out on 2019-08-12, and resolved in Arch with the 3.3-1 release of parted on 2019-10-11.[4]

      For older builds, a one-liner workaround was mentioned in the bug report, but the report also indicated that it did not seem to work properly for everyone.[5][6]

      It should be noted that this issue largely did not affect gparted, as the project included the patch in their build as of gparted version 0.26.0-1 (released 2016-04-29).[7]

      gparted on Wayland fails with «cannot open display: :0»

      This issue is caused by xwayland refusing access to gparted running as root . gparted developers implemented [8] a small workaround which temporarily adds root to the list of users allowed to connect to xwayland while the application is running.

      Источник

      Читайте также:  Как узнать производительность видеокарты windows 10
Оцените статью