Linux making file system

How to create and mount filesystems in Linux

Creating a file system writes information to the device and creates order of the empty space. This file system–related data consumes a small percentage of the space. The remaining space on the disk drive is split into small, consistently sized segments called blocks. Linux supports a number of file system types, some of which are described as follows.

Filesystem Description
ext2 High performance for fixed disk and removable media
ext3 Journaling version of ext2
ext4 Supports larger files and file system sizes
vfat MS-DOS file system useful when sharing files between Windows and Linux
XFS High-performance journaling file system
Btrfs Addresses scalability requirements of large storage systems

Creating Filesystems

The command to build a Linux file system on a device, or hard disk partition, is mkfs. The syntax for the command is:

The mkfs command is actually a front end for the different file system builder utilities such as mkfs.ext2 and mkfs.ext4. These utilities are executable directly from the command line. When using the mkfs wrapper, include the -t fstype option to specify the type of file system to be built. If not specified, the default file system type, ext2, is created.

To see which supported file system types are installed, use the ls /sbin/mkfs* command:

# ls -lrt /sbin/mkfs* -rwxr-xr-x. 1 root root 28624 Jun 10 2014 /sbin/mkfs.fat lrwxrwxrwx. 1 root root 8 Jan 7 2015 /sbin/mkfs.msdos -> mkfs.fat lrwxrwxrwx. 1 root root 8 Jan 7 2015 /sbin/mkfs.vfat -> mkfs.fat -rwxr-xr-x. 4 root root 96296 Aug 3 2017 /sbin/mkfs.ext4 -rwxr-xr-x. 4 root root 96296 Aug 3 2017 /sbin/mkfs.ext3 -rwxr-xr-x. 4 root root 96296 Aug 3 2017 /sbin/mkfs.ext2 -rwxr-xr-x. 1 root root 368464 Aug 4 2017 /sbin/mkfs.xfs -rwxr-xr-x. 1 root root 375240 Aug 6 2017 /sbin/mkfs.btrfs -rwxr-xr-x. 1 root root 37104 Dec 1 23:28 /sbin/mkfs.minix -rwxr-xr-x. 1 root root 36984 Dec 1 23:28 /sbin/mkfs.cramfs -rwxr-xr-x. 1 root root 11520 Dec 1 23:28 /sbin/mkfs

The mkdosfs, mkfs.msdos, and mkfs.vfat files are symbolic links to mkfs.fat.

Using mkfs

The default file system type created when using the mkfs command is ext2. As previously mentioned, mkfs is a wrapper that calls other file system build utilities. Therefore, any of the following commands create an ext2 file system on the specified device:

# mkfs /dev/xvdd1 # mke2fs /dev/xvdd1 # mkfs.ext2 /dev/xvdd1

To create an ext3 file system, use any of the following commands:

# mkfs –t ext3 /dev/xvdd1 # mke2fs –t ext3 /dev/xvdd1 # mkfs.ext3 /dev/xvdd1

To create an ext4 file system, use any of the following commands:

# mkfs –t ext4 /dev/xvdd1 # mke2fs –t ext4 /dev/xvdd1 # mkfs.ext4 /dev/xvdd1

Configuration File

A number of options are available to customize block size, fragment size, blocks per group, journal options, number of inodes, and other parameters. Without including any options, the defaults that are specified in the /etc/mke2fs.conf configuration file are used.

Читайте также:  Статистика популярности дистрибутивов линукс

File System Labels

A useful option for the file system build utilities is the -L name option. This assigns a label to the partition; this label can be used instead of the device name when mounting the file system. Labels are limited to a maximum size of 16 characters. For existing file systems, the e2label command is used to display or set a label.

File systems are automatically assigned a universally unique identifier (UUID). UUIDs can be used when mounting the file system. To display the UUID, the label, and the file system type, use the blkid command. The following examples illustrate creating different file systems, with and without a label, and displaying the information with the blkid command. To create an ext2 file system and display information, enter:

# mkfs /dev/xvdf1 # blkid /dev/xvdf1 /dev/xvdf1: UUID="41bae7c3-396a-436d-9764-d27d4ca3f17b" TYPE="ext2"

To create an ext3 file system and display information, enter:

# mkfs -t ext3 /dev/xvdf1 # blkid /dev/xvdf1 /dev/xvdf1: UUID="c8e958f4-e5d0-4404-8a9a-2cea24675fcd" SEC_TYPE="ext2" TYPE="ext3"

To create an ext4 file system, assign a label name, and display information, enter:

# mkfs -t ext4 -L "Test Label" /dev/xvdf1 # blkid /dev/xvdf1 /dev/xvdf1: LABEL="Test Label" UUID="687eb83f-c16f-4fa9-bb49-1621eed3a35d" TYPE="ext4"

Mounting File Systems

File systems on different partitions and removable devices, such as CDs, DVDs, or USB flash drives, must be attached to the directory hierarchy to be accessed. To attach a partition or device, a mount point must be created. A mount point is simply a directory created with the mkdir command. After a directory, or mount point, is created, attach the partition by using the mount command. Syntax for the mount command is:

# mount [options] device_file mount_point

The following example creates a mount point (/test) and attaches the partition:

# mkdir /test # mount /dev/xvdf1 /test

Alternatively, mount the partition or device by referencing the UUID or label. The following example displays the UUID and label, using the blkid command, and mounts the partition by referencing each:

# blkid /dev/xvdf1 /dev/xvdf1: LABEL="Test Label" UUID="687eb83f-c16f-4fa9-bb49-1621eed3a35d" TYPE="ext4"
# mount LABEL="Test Label" /test # mount UUID="687eb83f-c16f-4fa9-bb49-1621eed3a35d" /test

The mount command without any options displays all currently attached file systems:

# mount | grep test /dev/xvdf1 on /test type ext4 (rw,relatime,seclabel,data=ordered)

In this example, the /dev/xvdf1 partition is mounted on /test. The file system type is ext4 and is mounted for both reading and writing. The df command also displays mounted file systems. Example:

# df -hP /test Filesystem Size Used Avail Use% Mounted on /dev/xvdf1 923M 2.4M 857M 1% /test

The information in the proc file system displays mounted file systems. Example:

# cat /proc/mounts | grep test /dev/xvdf1 /test ext4 rw,seclabel,relatime,data=ordered 0 0

Mount Options

To specify mount options, use the –o flag followed by a comma-separated string of options. The following are some of the available options for the mount command:

  • auto: Allows the file system to be mounted automatically by using the mount –a command
  • loop: Mounts the image as a loop device
  • noauto: Disallows the automatic mount of the file system by using the mount –a command
  • noexec: Disallows the execution of binary files on the file system
  • nouser: Disallows an ordinary user (other than root) to mount and unmount the file system
  • remount: Remounts the file system in case it is already mounted
  • ro: Mounts the file system for reading only
  • rw: Mounts the file system for both reading and writing
  • user: Allows an ordinary user (other than root) to mount and unmount the file system
Читайте также:  Linux точка монтирования boot

For example, to mount the /dev/xvdf1 partition on the /test mount point as read-only with only the root user able to mount and unmount the file system, enter:

# mount –o nouser,ro /dev/xvdf1 /test

To mount an ISO image by using the loop device (assuming that the ISO image is present in the current directory and the mount point exist), enter:

# mount -o ro,loop rhel7-x86_64-dvd.iso /media/cdrom

Journaling Mount Options

The ext3 and ext4 file systems have three journaling levels that can be set with the -o option in the mount command or in the options section of /etc/fstab:

  • data=journal: The highest level. The one that does the most journaling. This writes the journal entries for all the data and metadata changes. All data is committed into the journal before being written into the main file system.
  • data=ordered: The default mode. All data is forced directly out to the main file system before its metadata is committed to the journal.
  • data=writeback: The lowest level. Data ordering is not preserved. Data can be written into the main file system after its metadata has been committed to the journal.

Unmounting File Systems

To unmount a file system, use the umount command. The partition name, the device name, or the mount point is used as an argument. Example:

# umount /dev/xvdd1 # umount /test

/etc/fstab File

The /etc/fstab file is called the file system mount table and contains all the information that the mount command needs to mount devices. When adding a new file system, create the appropriate entry in /etc/fstab to ensure that the file system is mounted at boot time. The following is an example of entries in the /etc/fstab file:

# cat /etc/fstab LABEL=centos_root / ext4 defaults 0 0 devpts /dev/pts devpts gid=5,mode=620 0 0 tmpfs /dev/shm tmpfs defaults 0 0 proc /proc proc defaults 0 0 sysfs /sys sysfs defaults 0 0 UUID=687eb83f-c16f-4fa9-bb49-1621eed3a35d /test ext4 defaults 0 0

The first column is the device to mount. The UUID or the label name should be used in place of the device name, because device names could change. The second column is the mount point, except the swap partition entry. The third column is the file system type. The fourth column specifies mount options. The fifth column is used by the dump command. The number 1 means to dump the file system and 0 means the file system does not need to be dumped. The last column is used by the fsck program to determine the order in which file system checks are done at reboot time. The root file system should be specified with a value of 1 and the other file systems should have a value of 2. A value of 0 does not check the file system.

Читайте также:  Настройка conky astra linux

Источник

Команда mkfs в Linux

Команда mkfs (Make file system) используется в Linux чаще всего для создания файловой системы в разделе жёсткого диска.

Команда Linux mkfs

Синтаксис

mkfs [параметры] [-t ] [параметры ФС] []

Опции

-t, —type= <тип>Тип файловой системы; ext2, если ничего не указано fs-options Параметры для программы создания реальной файловой системы Путь к используемому устройству Число используемых блоков устройства -V, —verbose Подробная информация о выполняемых действиях; указание параметра -V более одного раза приведет к тестовому запуску

Типы файловых систем

Вы можете увидеть список файловых систем, доступных для создания вашим дистрибутивом Linux. Для этого следует набрать в терминале команду и дважды нажать клавишу Tab:

Команда Linux mkfs, список доступных файловых систем

Эти варианты предлагают дистрибутивы Arch Linux и Ubuntu

Выбор файловой системы

Самой популярная файловая система Linux в настоящее время — Ext4. Она проверена, надёжна и является стандартной для ряда дистрибутивов. Ext4 позволяет уменьшить фрагментацию файлов и работать с очень большими дисками, разделами и файлами.

Создание файловой системы BFS вряд когда-либо потребуется, так как она является загрузочной и создаётся при установке Linux.

Системы MSDOS и FAT являются устаревшими и мало кому-нибудь нужны.

Система VFAT обычно используется на внешних носителях: флеш-накопителях, картах памяти.

Файловая система NTFS может потребоваться тем пользователям, которые хотят получить совместимость с операционной системой Windows.

Создание файловой системы

Помните! Все данные, находившиеся ранее на разделах будут безвозвратно утеряны!

Создаём файловую систему ext2 на /dev/sdb1 :

oleg@mobile:~:$ sudo mkfs -t ext2 /dev/sdb1 mke2fs 1.46.5 (30-Dec-2021) /dev/sdb1 contains a ext2 file system created on Sat Jul 2 11:34:38 2022 Proceed anyway? (y,N) y Creating filesystem with 3781376 4k blocks and 946560 inodes Filesystem UUID: d1be6ca8-ecd2-4e35-af67-5cceb323cb4e Superblock backups stored on blocks: 32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208 Allocating group tables: done Writing inode tables: done Writing superblocks and filesystem accounting information: done 

При создании файловой системы ext2 можно использовать команду mkfs и так:

Утилита mkfs без опций также создаст файловую систему ext2 по умолчанию.

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

Проверка устройства хранения на наличие бед-блоков:

oleg@mobile:~:$ sudo mkfs -c /dev/sdb1 mke2fs 1.46.5 (30-Dec-2021) /dev/sdb1 contains `DOS/MBR boot sector' data Proceed anyway? (y,N) y Creating filesystem with 3781376 4k blocks and 946560 inodes Filesystem UUID: d1cf78a6-aa45-41d7-9889-2e23c8103f06 Superblock backups stored on blocks: 32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208 Checking for bad blocks (read-only test): done Allocating group tables: done Writing inode tables: done Writing superblocks and filesystem accounting information: done 

Подобная проверка занимает значительное время.

Проверка типа файловой системы носителя:

oleg@mobile:~:$ sudo file -sL /dev/sdb1 /dev/sdb1: Linux rev 1.0 ext2 filesystem data, UUID=d1be6ca8-ecd2-4e35-af67-5cceb323cb4e (large files)

Выводы

Использование команды Linux mkfs не представит серьёзных трудностей даже при недостатке опыта. Необходимо лишь быть очень внимательным, ведь по ошибке можно навсегда распрощаться с данными, находившимися ранее на разделах диска.

Источник

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