Setting up linux file system

How to install xfs and create xfs file system on Debian/Ubuntu Linux

Table of contents

Install xfs on Debian Linux

Open the terminal app to update system and then install xfs packages:
$ sudo apt-get update
$ sudo apt-get upgrade
Use the apt command/apt-get command to install xfs:
$ sudo apt-get install xfsprogs
Sample outputs

Load xfs kernel module/driver

Now xfs related utilities are installed. However, it would be best if you loaded xfs Linux kernel driver/module too. In other words, type the following one time command:
$ sudo modprobe -v xfs
Sample outputs:

Verify that xfs loaded either using the grep command or lsmod command:
$ grep xfs /proc/filesystems
$ lsmod | grep xfs
$ modinfo xfs

See Linux Add or Remove a Linux Kernel Modules / Drivers for more info.

How to list available disks on a Debian or Ubuntu Linux

You need to use the fdisk command and then press [enter] key:
sudo fdisk -l
My disks:

WARNING : Be careful with disks names. Verify twice before formatting or creating new partitions. A wrong SSD/HDD name would result in data loss, and your /dev/DISK names might be different.

Источник

Работа с файловой системой Linux

Во время выполнения различных задач по администрированию системы может понадобится работать с файловой системой Linux, форматировать разделы, изменять их размер конвертировать файловые системы, выполнить дефрагментацию в Linux или восстановление файловых систем.

Многие из этих действий выполняются в графическом интерфейсе, многие и вовсе автоматически. Но может возникнуть ситуация, в которой придется делать все через терминал. Также при администрировании удаленных серверов работать с ними приходится только через ssh, а это означает недоступность графического интерфейса.

В этой статье мы рассмотрим как выполняется работа с файловой системой Linux в терминале. За основу возьмем семейство файловых систем ext2/3/4, так как они самые распространенные среди большого многообразия дистрибутивов Linux.

Основные команды

Для управления файловой системой ext в Linux используется целый набор команд из пакета e2progs. Сюда входят как команды для управления флагами файлов, создания и изменения файловых систем, так и утилиты для отладки файловой системы.

Рассмотрим основные утилиты, которые будем использовать:

  • badblocks — если у вас старый жесткий диск и на нем накопилось много битых блоков, вы можете с помощью этой утилиты пометить их все на уровне файловой системы, чтобы больше не использовать.
  • e2label — позволяет изменить метку раздела с файловой системой ext.
  • fsck — проверка файловой системы linux и исправление найденных ошибок
  • mkfs — позволяет создать файловую систему Linux.
  • resize2fs — изменить размер раздела с файловой системой
  • tune2fs — позволяет изменить файловую систему Linux, настроить ее параметры.

А теперь будет рассмотрена работа с файловой системой linux на примерах.

Работа с файловой системой в Linux

Перед тем как переходить к работе с реальным жестким диском важно попрактиковаться. Если сменить метку или проверить на битые сектора можно и рабочий диск, то создавать новую файловую систему, изменять ее размер, рискуя потерять данные на реальном диске не рекомендуется. Можно отделить небольшой раздел диска для экспериментов с помощью Gparted и выполнять все действия в нем. Допустим, у нас этот раздел будет называться /dev/sda6.

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

Создать файловую систему linux, семейства ext, на устройстве можно с помощью команды mkfs. Ее синтаксис выглядит следующим образом:

sudo mkfs -t тип устройство

Доступны дополнительные параметры:

  • — проверить устройство на наличие битых секторов
  • -b — размер блока файловой системы
  • -j — использовать журналирование для ext3
  • -L — задать метку раздела
  • -v — показать подробную информацию о процессе работы
  • -V — версия программы

Создаем файловую систему на нашем устройстве. Будем создавать ext3:

sudo mkfs -t ext4 -L root /dev/sda6

Creating filesystem with 7847168 4k blocks and 1962240 inodes
Filesystem UUID: 3ba3f7f5-1fb2-47af-b22c-fa4ca227744a
Superblock backups stored on blocks:
32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,
4096000
Allocating group tables: done
Writing inode tables: done
Creating journal (32768 blocks): done
Writing superblocks and filesystem accounting information: done

Изменение метки файловой системы

Утилита e2label позволяет изменить или посмотреть метку раздела диска. Принимает всего два параметра — устройство и новую метку если нужно.

sudo e2label /dev/sda6

sudo e2label /dev/sda6 root1

Настройка файловой системы linux

Различные параметры файловой системы, такие как размер блока данных, иноды или зарезервированное место под данные пользователя root можно настроить. Для этого существует утилита tune2fs.

Синтаксис команды очень прост:

$ tune2fs опции устройство

Поддерживаются следующие опции:

  • -j — создать файл журнала. Позволяет превратить файловую систему ext2 в ext3.
  • -J — настроить параметры журнала
  • -l — получить содержимое суперблока
  • -L — изменить метку раздела
  • -m — изменить процент дискового пространства, зарезервированного для суперпользователя
  • -M — изменить последнюю папку монтирования
  • -U — задать UUID файловой системы
  • -C — изменить значение счетчика монтирования
  • -T — изменить последнюю дату проверки файловой системы
  • — изменить периодичность проверок файловой системы с помощью fsck
  • -O — изменить опции файловой системы.

Изменить размер зарезервированного места для суперпользователя до пяти процентов:

sudo tune2fs -m 5 /dev/sda6

Setting reserved blocks percentage to 5% (392358 blocks)

Посмотреть информацию из суперблока, эта команда показывает всю доступную информацию параметрах файловой системы:

Filesystem volume name: root
Last mounted on: /
Filesystem UUID: 3ba3f7f5-1fb2-47af-b22c-fa4ca227744a
Filesystem magic number: 0xEF53
Filesystem revision #: 1 (dynamic)
Filesystem features: has_journal ext_attr resize_inode dir_index filetype extent flex_bg spar
se_super large_file huge_file uninit_bg dir_nlink extra_isize
Filesystem flags: signed_directory_hash
Default mount options: user_xattr acl
Filesystem state: clean
Errors behavior: Continue
Filesystem OS type: Linux

Изменить счетчик количества монитрований:

tune2fs -C 0 /dev/sda6

Setting current mount count to 0

Думаю тут смысл понятен, нужно только немного со всем этим поэкспериментировать.

С помощью опции -O мы вообще можем превратить нашу ext3 в ext4 следующей командой:

sudo tune2fs -O extents,uninit_bg,dir_index

После этого действия нужно выполнить проверку файловой системы на ошибки в fsck. Подробнее об этом поговорим ниже.

sudo fsck -np /dev/sda6

Таким образом вы можете изменить файловую систему linux, и настроить по своему усмотрению любые ее параметры.

Изменение размера файловой системы Linux

Раньше такая функция поддерживалась в утилите parted, но потом ее убрали и для этого действия приходится использовать утилиту из набора e2fsprogs — resize2fs.

Запустить утилиту очень просто. Ей нужно передать всего два параметра:

$ resize2fs [опции] устройство размер

Доступны также опции:

  • -M уменьшить файловую систему до минимального размера
  • -f — принудительное изменение, не смотря на потерю данных
  • -F — очистить буфер файловой системы

Размер передается, как и во многих других утилитах, целым числом с указанием единиц измерения, например, 100М или 1G.

Для примера уменьшим размер нашего раздела до 400 Мегабайт:

sudo resize2fs /dev/sda6 400M

Resizing the filesystem on /dev/sda7 to 102400 (4k) blocks.
The filesystem on /dev/sda7 is now 102400 blocks long

Проверка файловой системы Linux

При неправильном отключении носителей или неожиданном отключении питания, файловая система Linux может быть повреждена. Обычно проверка корневой файловой системы и домашнего каталога на ошибки выполняется во время загрузки. Но если эта проверка не была выполнена или нужно поверить другой носитель, придется все делать вручную. Для этого есть утилита fsck.

$ fsck [опции] устройство

  • -p — автоматическое восстановление
  • -n — только проверка, без восстановления
  • -y — ответить да на все запросы программы
  • — проверить на битые сектора (аналог badblocks
  • -f — принудительная проверка, даже если раздел помечен как чистый
  • -j — внешний журнал файловой системы

Проверка файловой системы Linux выполняется такой командой, проверим диск /dev/sda6, заметьте, что диск должен быть не примонтирован:

sudo fsck -a /dev/sda6

root: clean, 11/32704 files, 37901/102400 blocks

Дефрагментация файловой системы

Хотя и фрагментация нехарактерное явление для файловых систем семейства ext, при очень интенсивном использовании может накапливаться фрагментированость, что будет замедлять работу файловой системы. Для дефрагментации можно использовать стандартную утилиту e4defrag. Просто выполните:

Чтобы проверить нужна ли дефрагментация в Linux выполните эту же команду с опцией -c:

Total/best extents 26247/24953
Average size per extent 1432 KB
Fragmentation score 0
[0-30 no problem: 31-55 a little bit fragmented: 56- needs defrag]
This device (/dev/sda6) does not need defragmentation.
Done.

В поле Fragmentation score отображен процент фрагментации, как видите, у меня 0, нормой считается до 30, 31-55 небольшие проблемы, и больше 56 — нужна дефрагментация.

Выводы

В одной из предыдущих статей мы рассмотрели как выполняется разметка диска с помощью parted. Из этой статьи вы узнали все что нужно о работе с файловой системой. Теперь у вас не возникнет проблем если у вас вдруг не будет доступа к графическим утилитам и нужно будет исправлять ошибки или настраивать файловую систему. Если остались вопросы, спрашивайте в комментариях!

Источник

Как исправить read only file system в Linux

Ошибка read only file system может возникнуть при загрузке с LiveCD диска или в режиме восстановления вашего дистрибутива. Она означает, что файловая система в которую вы пытаетесь вести запись примонтирована только для чтения. Этому может быть несколько причин. Есть файловые системы, которые доступны только для чтения это файловая система оптических дисков — ISO, а также файловая система образов SquashFS.

С такими файловыми системами вы сделать ничего не сможете. Для изменения данных в них, надо распаковать образ, изменить данные и запаковать его обратно. Но что касается обычных файловых систем, таких как EXT4, BTRFS, XFS, то их можно монтировать и для чтения и для записи.

Ошибка read only file system в Linux

В этой небольшой статье мы рассмотрим как исправить read only file system Linux перемонтировав файловую систему для записи. Первым делом надо определиться с точкой монтирования, для которой надо разрешить запись. Попытаемся создать файл в корневом каталоге:

Ошибка, файловая система корневого каталога доступна только для чтения. Чтобы посмотреть все точки монтирования доступные в системе выполните в терминале:

mount | grep /dev/sd

В данном случае, корневая файловая система и есть точкой монтирования. Но у вас, например, возникнут проблемы с созданием файла в домашней папке, то надо будет уже перемонтировать /home. Смотрите внимательно. Когда точка монтирования выбрана, осталось её примонтировать с правами на запись:

sudo mount -o remount,rw /

sudo mount -o remount,rw /home

После этого вы сможете создать файл без каких-либо проблем. После завершения работы, во избежание повреждения данных при перезагрузке, желательно перемонтировать файловую систему обратно в режим только для чтения:

sudo mount -o remount,ro /

Теперь вы знаете что означает эта ошибка и как с ею справится. Если у вас остались вопросы, спрашивайте в комментариях!

Источник

Setting up disks manually

The menu choices that are provided by setup-alpine can not cover all needs, however, it’s possible to:

  • Call setup-disk directly, instead of through setup-alpine , and pass some specific partitioning parameters to it.
  • Set up the partitions and filesystems manually (to the desired details) and tell setup-disk to install to the prepared target mountpoint.

Contents

Using setup-alpine (setup-disk) features

For «diskless» and «data» disk mode installs

This requires some manual steps, as long as the setup-scripts auto-detect usable partitions only on *removable* devices (not internal harddisks). They do not support creating new, writable partitions to be used by Alpine.

How to prepare writable storage space is explained in the section manual partitioning, below.

For «sys» disk mode installs

Some information on this page may be incomplete or outdate.
(Last edited by Bt129 on 28 Jun 2021.)

Disk layouts

It is possible to have one or more of RAID, encrypted, and/or Logical Volume on your / (root) volume. However, the Alpine init script only knows how to handle them when they’re layered in that order, and your initram and extlinux.conf files in the /boot partition are configured properly.

Your /boot directory cannot reside on an encrypted or LVM volume, at least not with Alpine’s default bootloader (extlinux). (Grub2 can deal with /boot being on an LVM volume.) The usual practice is to create a small partition for /boot , then devote the rest of your disk to a separate partition on which you layer one or more of RAID, encryption, and/or Logical Volumes.

Sometimes /boot is also set up as a mirrored (RAID1) volume. However, this is just for post-init access. That way, when you write a new kernel or bootloader config file to /boot , it gets written to multiple physical partitions. During the pre-init, bootloader phase, only one of those partitions will be read from.

A typical setup might look like this:

In a three-disk system, the /boot would still be RAID1, but the larger partition might, in that case, be RAID5.

setup-disk will automatically build a RAID array if you supply the -r switch, or if you specify more than one device.

If you want to build your RAID array manually, see Setting up a software RAID array. Then you can add additional layers of encryption and/or Logical Volumes, or just assemble the RAID array, and supply the /dev/mdi device directly to setup-disk. When you’re finished, be sure to disassemble the RAID array before rebooting.

If setup-disk sees that you’re using RAID, either because you gave it the -r switch, or multiple devices, or a /dev/mdi device, then it will set up your initramfs and extlinux.conf file properly. However, in other cases, such as when you’re also using encryption, or you invoke setup-disk with a mounted directory argument, these might not be properly set up for RAID. In that case, you may need to manually edit/rebuild them. The following assumes that $MNT holds the root directory you’re installing into:

echo «/sbin/mdadm» > $MNT/etc/mkinitfs/files.d/raid echo «/etc/mdadm.conf» >> $MNT/etc/mkinitfs/files.d/raid # edit $MNT/etc/mkinitfs/mkinitfs.conf to make sure features=». » # includes raid (this field is space-separated and quoted) mkinitfs -c $MNT/etc/mkinitfs/mkinitfs.conf -b $MNT # edit $MNT/etc/update-extlinux.conf to make sure modules=. contains # raid1 or raid456 (whichever your / is on; this field is comma-separated) # also check the root= setting extlinux —raid —install $MNT/boot —update

You might also need to manually tweak $MNT/etc/fstab . And you might need to copy /usr/share/syslinux/mbr.bin to your disk’s MBR.

Encryption

See Setting up encrypted volumes with LUKS. You can add an additional Logical Volume layer, or just unlock the volume you’ve created (using cryptsetup luksOpen . ), and supply the /dev/mapper/something device directly to setup-disk. When you’re finished, be sure to relock the volume (using cryptsetup luksClose . ) before rebooting.

If you install your / (root) on an encrypted volume, you’ll need to manually edit/rebuild your initram and your extlinux.conf file. The following assumes that $MNT holds the root directory you’re installing into, that you’ve created the cryptvolume on the device /dev/md2 , and that you want to unlock the encrypted volume into a virtual volume named «crypt»:

# edit $MNT/etc/mkinitfs/mkinitfs.conf to make sure features=». » # includes cryptsetup (this field is space-separated and quoted) mkinitfs -c $MNT/etc/mkinitfs/mkinitfs.conf -b $MNT # edit $MNT/etc/update-extlinux.conf to make sure default_kernel_opts=». » # contains cryptroot=/dev/md1 and cryptdm=crypt (this field is also space-separated and quoted) # also check the root= setting extlinux —install $MNT/boot —update

You might also need to manually tweak $MNT/etc/fstab .

setup-disk will automatically build and use volumes in a LVM group if you supply the -L switch.

If you instead want to build your LVM system manually, see Setting up Logical Volumes with LVM. Then vgchange -ay , format and mount your volumes, and supply the root mountpoint to setup-disk. When you’re finished, be sure to

umount . vgchange -an

If setup-disk sees that you’re using LVM, perhaps because you gave it the -L switch, then it will set up your initram and extlinux.conf file properly. However, in other cases, these might not be properly set up. In that case, you may need to manually edit/rebuild them. The following assumes that $MNT holds the root directory you’re installing into:

# edit $MNT/etc/mkinitfs/mkinitfs.conf to make sure features=». » # includes lvm (this field is space-separated and quoted) mkinitfs -c $MNT/etc/mkinitfs/mkinitfs.conf -b $MNT # edit $MNT/etc/update-extlinux.conf to make sure root= is set correctly extlinux —install $MNT/boot —update

You might also need to manually tweak $MNT/etc/fstab .

Manual partitioning

For «diskless» and «data» disk mode installs

The installation image enviroment may have only the very basic busybox built-in fdisk command available. However, alpine allows you to install more complete partitioning tool packages like sfdisk (scriptable fdisk), gptfdisk , parted (CLI), cfdisk (text menus), or even gparted (after setting up a graphical environment).

The following example installs cfdisk , looks for existing partitions, and runs cfdisk against /dev/sdX :

  • Be aware of this Bug: The APKOVL loading of diskless setups doesn’t work on btrfs and xfs filesystems, or nvme-based devices => So, for the moment, use only ext4 filesystem partitions on classic drives to store diskless mode states.

The following creates an ext4 partition with disabled journaling, to reduce write operations and allow the disk to spin down after the .apkovl and the packages have been read from the partition during the boot.

For «sys» disk mode installs

setup-disk will by default set up a root partition, a separate /boot partition and a swap partition. If you want a different layout, you can manually create the partitions, filesystems and mount them on /mnt (or any other mount point) then run:

setup-disk will install your running system on the mounted root, detect your file system layout and generate an fstab.

If you’re using the MBR, you are responsible for making the proper partition bootable and make sure the MBR is OK for extlinux. If you’re going to use EFI, make sure you set BOOTLOADER=grub and USE_EFI=1 , and that grub-efi and efibootmgr are installed before running setup-disk .

Dual-booting

Other needs

Setting up swap

  1. create a partition with the type set to «linux swap» (82) (If you’re going to use a logical volume for swap, skip this step and lvcreate that instead.)
  2. mkswap /dev/sda2
  3. echo -e «/dev/sda2 none swap sw 0 0» >> /mnt/etc/fstab
  4. swapon /dev/sda2 (or rc-service swap start )

will show how much swap space is available (in MB).

If you prefer maximum speed, you don’t need configure any raid devices for swap. Just add 2 swap partitions on different disks and linux will stripe them automatically. The downside is that the moment one disk fails, the system will go down. For better reliability, put swap on RAID1.

Источник

Читайте также:  Загрузка графической оболочки astra linux
Оцените статью
Tutorial requirements
Requirements Debian/Ubuntu Linux
Root privileges Yes
Difficulty Easy
Est. reading time 10m