7 примеров команд Linux fdisk для управления разделами жесткого диска

В дистрибутивах Linux fdisk – лучший инструмент для управления разделами диска. fdisk – это текстовая утилита.

С помощью fdisk вы можете создать новый раздел, удалить существующий раздел или изменить существующий раздел.

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

Помните, что для любого отдельного раздела требуется минимальный размер 40 МБ.


В этой статье мы рассмотрим, как использовать команду fdisk на практических примерах.

Предупреждение: не удаляйте, не изменяйте и не добавляйте раздел, если вы не знаете, что делаете. Вы потеряете свои данные!

1. Просмотреть все существующие разделы диска, используя fdisk -l

Перед созданием нового раздела или изменением существующего раздела вы можете просмотреть все доступные разделы в системе.

Используйте fdisk -l для просмотра всех доступных разделов, как показано ниже.

# fdisk -l

Disk /dev/sda: 80.0 GB, 80026361856 bytes
255 heads, 63 sectors/track, 9729 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0xf6edf6ed

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1               1        1959    15735636    c  W95 FAT32 (LBA)
/dev/sda2            1960        5283    26700030    f  W95 Ext'd (LBA)
/dev/sda3            5284        6528    10000462+   7  HPFS/NTFS
/dev/sda4            6529        9729    25712032+   c  W95 FAT32 (LBA)
/dev/sda5   *        1960        2661     5638752   83  Linux
/dev/sda6            2662        2904     1951866   83  Linux
/dev/sda7            2905        3147     1951866   83  Linux
/dev/sda8            3148        3264      939771   82  Linux swap / Solaris
/dev/sda9            3265        5283    16217586    b  W95 FAT32

Выше приведен список разделов со всех подключенных жестких дисков. Если в системе имеется несколько дисков, список разделов упорядочивается по имени устройства /dev. Например, /dev/sda, /dev/sdb, /dev/sdc и так далее.

2. Просмотрите разделы определенного жесткого диска, используя fdisk -l / dev / sd {a}

Чтобы просмотреть все разделы жесткого диска / dev / sda, выполните следующие действия.

# fdisk -l /dev/sda

Просмотреть все команды fdisk с помощью команды fdisk m

Используйте команду fdisk m, чтобы просмотреть все доступные команды fdisk, как показано ниже.

# fdisk  /dev/sda

The number of cylinders for this disk is set to 9729.
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., old versions of LILO)
2) booting and partitioning software from other OSs
   (e.g., DOS FDISK, OS/2 FDISK)

Command (m for help): m
Command action
   a   toggle a bootable flag
   b   edit bsd disklabel
   c   toggle the dos compatibility flag
   d   delete a partition
   l   list known partition types
   m   print this menu
   n   add a new partition
   o   create a new empty DOS partition table
   p   print the partition table
   q   quit without saving changes
   s   create a new empty Sun disklabel
   t   change a partition's system id
   u   change display/entry units
   v   verify the partition table
   w   write table to disk and exit
   x   extra functionality (experts only)

3. Удалите раздел жесткого диска с помощью команды fdisk d

Предположим, вам нравится объединять несколько разделов (например, / dev / sda6, / dev / sda7 и / dev / sda8) в один раздел диска. Для этого вы должны сначала удалить все эти отдельные разделы, как показано ниже.

# fdisk /dev/sda                                                 

The number of cylinders for this disk is set to 9729.
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., old versions of LILO)
2) booting and partitioning software from other OSs
   (e.g., DOS FDISK, OS/2 FDISK)                               

Command (m for help): p

Disk /dev/sda: 80.0 GB, 80026361856 bytes
255 heads, 63 sectors/track, 9729 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0xf6edf6ed

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1               1        1959    15735636    c  W95 FAT32 (LBA)
/dev/sda2            1960        5283    26700030    f  W95 Ext'd (LBA)
/dev/sda3            5284        6528    10000462+   7  HPFS/NTFS
/dev/sda4            6529        9729    25712032+   c  W95 FAT32 (LBA)
/dev/sda5   *        1960        2661     5638752   83  Linux
/dev/sda6            2662        2904     1951866   83  Linux
/dev/sda7            2905        3147     1951866   83  Linux
/dev/sda8            3148        3264      939771   82  Linux swap / Solaris
/dev/sda9            3265        5283    16217586    b  W95 FAT32

Command (m for help): d
Partition number (1-9): 8

Command (m for help): d
Partition number (1-8): 7

Command (m for help): d
Partition number (1-7): 6

Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.

WARNING: Re-reading the partition table failed with error 16: Device or resource busy.
The kernel still uses the old table. The new table will be used at
the next reboot or after you run partprobe(8) or kpartx(8)
Syncing disks.

4. Создайте новый раздел на диске с определенным размером, используя команду fdisk n

После удаления всех существующих разделов вы можете создать новый раздел, используя все доступное пространство, как показано ниже.

# fdisk  /dev/sda

The number of cylinders for this disk is set to 9729.
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., old versions of LILO)
2) booting and partitioning software from other OSs
   (e.g., DOS FDISK, OS/2 FDISK)

Command (m for help): n
First cylinder (2662-5283, default 2662):
Using default value 2662
Last cylinder, +cylinders or +size{K,M,G} (2662-3264, default 3264):
Using default value 3264

В приведенном выше примере команда fdisk n используется для создания нового раздела с определенным размером. При создании нового раздела он ожидает следующие два ввода.

  • Номер начального цилиндра создаваемой перегородки (Первый цилиндр).
  • Размер раздела (или) номера последнего цилиндра (Последний цилиндр, + цилиндры или + размер).

Помните, что после любых изменений вы должны выполнить команду fdisk write (w).

Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.

WARNING: Re-reading the partition table failed with error 16: Device or resource busy.
The kernel still uses the old table. The new table will be used at
the next reboot or after you run partprobe(8) or kpartx(8)
Syncing disks.

После создания раздела отформатируйте его с помощью команды mkfs, как показано ниже.

# mkfs.ext3 /dev/sda7

5. Просмотр размера существующего раздела с помощью fdisk -s

Как показано ниже, fdisk -s отображает размер раздела в блоках.

# fdisk -s /dev/sda7
4843566

Вышеуказанный вывод соответствует примерно 4900 МБ.

6. Переключите флаг загрузки раздела с помощью команды fdisk a

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

Если вы не знаете, почему вы это делаете, вы испортите свою систему.

# fdisk /dev/sda

The number of cylinders for this disk is set to 9729.
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., old versions of LILO)
2) booting and partitioning software from other OSs
   (e.g., DOS FDISK, OS/2 FDISK)                               

Command (m for help): p

Disk /dev/sda: 80.0 GB, 80026361856 bytes
255 heads, 63 sectors/track, 9729 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0xf6edf6ed

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1               1        1959    15735636    c  W95 FAT32 (LBA)
/dev/sda2            1960        5283    26700030    f  W95 Ext'd (LBA)
/dev/sda3            5284        6528    10000462+   7  HPFS/NTFS
/dev/sda4            6529        9729    25712032+   c  W95 FAT32 (LBA)
/dev/sda5   *        1960        2661     5638752   83  Linux
/dev/sda6            3265        5283    16217586    b  W95 FAT32
/dev/sda7            2662        3264     4843566   83  Linux

Partition table entries are not in disk order

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

Command (m for help): p

Disk /dev/sda: 80.0 GB, 80026361856 bytes
255 heads, 63 sectors/track, 9729 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0xf6edf6ed

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1               1        1959    15735636    c  W95 FAT32 (LBA)
/dev/sda2            1960        5283    26700030    f  W95 Ext'd (LBA)
/dev/sda3            5284        6528    10000462+   7  HPFS/NTFS
/dev/sda4            6529        9729    25712032+   c  W95 FAT32 (LBA)
/dev/sda5            1960        2661     5638752   83  Linux
/dev/sda6            3265        5283    16217586    b  W95 FAT32
/dev/sda7            2662        3264     4843566   83  Linux

Partition table entries are not in disk order

Command (m for help):

Как видно выше, флаг загрузки отключен на разделе /dev/sda5.

7. Исправьте порядок таблицы разделов с помощью команды fdisk Expert f

Когда вы удаляете логический раздел и воссоздаете его снова, вы можете столкнуться с проблемой «раздел из строя». т.е. сообщение об ошибке «Записи таблицы разделов не в порядке диска».

Например, когда вы удаляете три логических раздела (sda6, sda7 и sda8) и создаете новый раздел, вы можете ожидать, что имя нового раздела будет sda6. Но система, возможно, создала новый раздел как sda7. Это связано с тем, что после удаления разделов раздел sda9 был перемещен как sda6, а свободное пространство перемещено до конца.

Чтобы устранить эту проблему с порядком разделов и назначить sda6 только что созданному разделу, выполните экспертную команду f, как показано ниже.

 $ fdisk  /dev/sda

The number of cylinders for this disk is set to 9729.
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., old versions of LILO)
2) booting and partitioning software from other OSs
   (e.g., DOS FDISK, OS/2 FDISK)                               

Command (m for help): p

Disk /dev/sda: 80.0 GB, 80026361856 bytes
255 heads, 63 sectors/track, 9729 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0xf6edf6ed                     

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1               1        1959    15735636    c  W95 FAT32 (LBA)
/dev/sda2            1960        5283    26700030    f  W95 Ext'd (LBA)
/dev/sda3            5284        6528    10000462+   7  HPFS/NTFS
/dev/sda4            6529        9729    25712032+   c  W95 FAT32 (LBA)
/dev/sda5   *        1960        2661     5638752   83  Linux
/dev/sda6            3265        5283    16217586    b  W95 FAT32
/dev/sda7            2662        3264     4843566   83  Linux          

Partition table entries are not in disk order

Command (m for help): x

Expert command (m for help): f
Done.

Expert command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.

WARNING: Re-reading the partition table failed with error 16: Device or resource busy.
The kernel still uses the old table. The new table will be used at
the next reboot or after you run partprobe(8) or kpartx(8)
Syncing disks.

Как только порядок таблиц разделов будет установлен, вы больше не будете получать сообщение об ошибке «Partition table entries are not in disk order».

# fdisk -l

Disk /dev/sda: 80.0 GB, 80026361856 bytes
255 heads, 63 sectors/track, 9729 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0xf6edf6ed

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1               1        1959    15735636    c  W95 FAT32 (LBA)
/dev/sda2            1960        5283    26700030    f  W95 Ext'd (LBA)
/dev/sda3            5284        6528    10000462+   7  HPFS/NTFS
/dev/sda4            6529        9729    25712032+   c  W95 FAT32 (LBA)
/dev/sda5   *        1960        2661     5638752   83  Linux
/dev/sda6            2662        3264     4843566   83  Linux
/dev/sda7            3265        5283    16217586    b  W95 FAT32