Arch install руководство

Состояние перевода: На этой странице представлен перевод статьи Installation guide. Дата последней синхронизации: 3 октября 2022. Вы можете помочь синхронизировать перевод, если в английской версии произошли изменения.

Этот документ является руководством по установке Arch Linux с помощью системы, загруженной с официальным установочным образом. Данный образ включает в себя специальные возможности, описанные на странице Install Arch Linux with accessibility options. Также на странице Category:Installation process доступны альтернативные методы установки.

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

Более подробные инструкции приведены в соответствующих статьях ArchWiki и на страницах справочных руководств (man) различных программ. Ссылки и на то, и на другое присутствуют в этом руководстве. Также вы можете получить помощь в IRC-канале и на англоязычном и русскоязычном форумах Arch Linux.

Arch Linux способен работать на любой x86_64-совместимой машине, имеющей хотя бы 512 МиБ ОЗУ, однако понадобится больше памяти для загрузки live-системы.[1] Базовая установка занимает меньше 2 ГиБ дискового пространства. Поскольку для процесса установки требуется получать пакеты из удалённого репозитория, необходимо работающее интернет-соединение.

Перед установкой

Загрузка установочного образа

В зависимости от желаемого способа загрузки, скачайте образ ISO или netboot (а также соответствующую подпись GnuPG) со страницы загрузок.

Проверка подписи

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

На системах с установленным GnuPG вы можете сделать это, скачав ISO PGP signature (ссылка на него есть на странице загрузок в разделе Checksums) в каталог с образом и выполнив команду:

$ gpg --keyserver-options auto-key-retrieve --verify archlinux-версия-x86_64.iso.sig

Также можно проверить подпись из установленного Arch Linux:

$ pacman-key -v archlinux-версия-x86_64.iso.sig

Примечание:

  • Самой подписью можно манипулировать, если загрузить её с зеркала, а не с archlinux.org, как указано выше. В этом случае убедитесь, что открытый ключ, который используется для декодирования подписи, подписан другим надёжным ключом. Команда gpg выведет отпечаток (fingerprint) открытого ключа.
  • Ещё один метод проверки подлинности подписи — убедиться, что отпечаток открытого ключа идентичен отпечатку ключа разработчиков Arch Linux, которые подписали ISO-образ. Для получения дополнительной информации о процессе проверки подлинности открытых ключей смотрите статью Wikipedia:ru:Криптосистема с открытым ключом.

Подготовка установочного носителя

Установочный образ можно загрузить на конечном устройстве с помощью USB-накопителя, оптического диска или сети (при помощи PXE) — следуйте соответствующей статье для подготовки установочного носителя.

Загрузка live-окружения

Примечание: Установочные образы Arch Linux не поддерживают Secure Boot, в связи с чем необходимо отключить данную функцию перед загрузкой. Однако при желании возможно настроить Secure Boot после завершения установки Arch Linux.

  1. Загрузите устройство с установочного носителя с Arch Linux. Обычно при включении компьютера нажимается специальная клавиша (иногда она указывается на заставке) во время фазы POST для выбора загрузочного устройства. Обратитесь к руководству вашей материнской платы для получения более подробных инструкций.
  2. Когда появится меню установочного носителя, выберите Arch Linux install medium и нажмите Enter для входа в установочное окружение.
  3. Вы загрузитесь в первую виртуальную консоль в качестве root-пользователя и увидите приглашение командной оболочки Zsh.

Чтобы переключиться на другую виртуальную консоль в процессе установки (например, для просмотра этого руководства в Lynx), используйте горячие клавиши Alt+стрелка. Для редактирования файлов доступны программы mcedit(1), nano и vim. Список пакетов, присутствующих в установочном образе, доступен на странице pkglist.x86_64.txt.

Установка раскладки клавиатуры

По умолчанию используется раскладка консоли US. Чтобы посмотреть список доступных раскладок, запустите:

# ls /usr/share/kbd/keymaps/**/*.map.gz

Чтобы выбрать раскладку, передайте имя соответствующего файла команде loadkeys(1), не указывая полного пути и расширения. Например, чтобы выбрать русскую раскладку, запустите:

# loadkeys ru

Консольные шрифты расположены в каталоге /usr/share/kbd/consolefonts/ и могут быть выбраны аналогичным способом с помощью команды setfont(8).

Проверка режима загрузки

Чтобы проверить режим загрузки, просмотрите содержимое каталога efivars:

# ls /sys/firmware/efi/efivars

Если содержимое отображается без каких-либо ошибок, система загружена в режиме UEFI. Если же такого каталога не существует, возможно, система загружена в режиме BIOS (или CSM). Если система загрузилась не в том режиме, который вам нужен, обратитесь к руководству пользователя вашей материнской платы.

Соединение с интернетом

Для настройки сетевого соединения в live-окружении выполните следующие действия:

  • Убедитесь, что ваш сетевой интерфейс обнаружен и включён, например, с помощью ip-link(8):
    # ip link
  • Если планируется использовать Wi-Fi или WWAN, убедитесь, что беспроводная карта не заблокирована с помощью rfkill.
  • Подключитесь к сети:
    • Ethernet: подключите кабель.
    • Wi-Fi: подключитесь к беспроводной сети с помощью iwctl.
    • Мобильный широкополосный модем: подключитесь к мобильной сети с помощью утилиты mmcli.
  • Настройте сетевые соединения:
    • DHCP: установка динамического IP-адреса и адреса DNS-сервера (при помощи systemd-networkd и systemd-resolved) должна срабатывать автоматически для проводных и беспроводных сетевых интерфейсов.
    • Статический IP: смотрите Настройка сети#Статический IP-адрес.
  • Соединение можно проверить с помощью утилиты ping:
    # ping archlinux.org

Примечание: Установочный образ включает в себя преднастроенные и активированные службы systemd-networkd, systemd-resolved, iwd и ModemManager. В случае с установленной системой необходима будет ручная настройка и активация данных служб.

Синхронизация системных часов

В live-окружении по умолчанию включен systemd-timesyncd, который выполнит синхронизацию времени автоматически после подключения интернета.

Чтобы удостовериться, что время задано правильно, используйте timedatectl(1):

# timedatectl status

Разметка дисков

Когда запущенная система распознает накопители, они становятся доступны как блочные устройства, например, /dev/sda, /dev/nvme0n1 или /dev/mmcblk0. Чтобы посмотреть их список, используйте lsblk или fdisk.

# fdisk -l

Результаты, оканчивающиеся на rom, loop и airoot, можно игнорировать.

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

  • Раздел для корневого каталога /.
  • Для загрузки в режиме UEFI также необходим системный раздел EFI.

Если вы хотите создать составное блочное устройство для LVM, шифрования системы или RAID, сделайте это сейчас.

Для изменения таблицы разделов используйте fdisk или parted. Например:

# fdisk /dev/диск_для_разметки

Примечание:

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

Примеры схем

UEFI с GPT

Точка монтирования Раздел Тип раздела Рекомендуемый размер
/mnt/boot1 /dev/системный_раздел_efi системный раздел EFI Минимум 300 МиБ
[SWAP] /dev/раздел_подкачки Linux swap Более 512 МиБ
/mnt /dev/корневой_раздел Linux x86-64 root (/) Остаток
  1. Можно использовать другие точки монтирования, например /mnt/efi, если используемый загрузчик будет способен загрузить ядро и initramfs с корневого раздела. Смотрите соответствующее предупреждение в статье Процесс загрузки Arch#Загрузчик.
BIOS с MBR

Точка монтирования Раздел Тип раздела Рекомендуемый размер
[SWAP] /dev/раздел_подкачки Linux swap Более 512 МиБ
/mnt /dev/корневой_раздел Linux Остаток

Также смотрите Разметка дисков#Примеры схем.

Форматирование разделов

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

Например, чтобы отформатировать /dev/корневой_раздел в Ext4, выполните следующую команду:

# mkfs.ext4 /dev/корневой_раздел

Если вы создали раздел для подкачки (swap), инициализируйте его с помощью утилиты mkswap(8):

# mkswap /dev/раздел_подкачки

Примечание: В случае с многоуровневыми (stacked) блочными устройствами замените /dev/*_раздел соответствующим путём к блочному устройству.

Если вы создали системный раздел EFI, отформатируйте его в FAT32 с помощью mkfs.fat(8).

Важно: Выполняйте форматирование, только если вы создали новый раздел в процессе разметки. Если системный раздел EFI уже существует, его форматирование уничтожит загрузчики других установленных операционных систем.

# mkfs.fat -F32 /dev/системный_раздел_efi

Монтирование разделов

Смонтируйте корневой раздел в каталог /mnt. Например, если корневой раздел — /dev/корневой_раздел, выполните следующую команду:

# mount /dev/корневой_раздел /mnt

Создайте точки монтирования для всех остальных разделов (например, /mnt/efi) и примонтируйте соответствующие разделы.

Совет: Команда mount(8), запущенная с опцией --mkdir, автоматически создаст требуемую точку монтирования. Можно создать их и вручную с помощью mkdir(1).

Для UEFI примонтируйте системный раздел EFI:

# mount --mkdir /dev/системный_раздел_efi /mnt/boot

Если вы ранее создали раздел подкачки (swap), активируйте его с помощью swapon(8):

# swapon /dev/раздел_подкачки

В дальнейшем genfstab(8) обнаружит смонтированные файловые системы и пространство подкачки.

Установка

Выбор зеркал

Пакеты для установки должны скачиваться с серверов-зеркал, прописанных в файле /etc/pacman.d/mirrorlist. В установочном образе, после подключения к сети, reflector обновит список зеркал (выбрав 20 наиболее актуальных HTTPS-зеркал) и отсортирует их по скорости загрузки.

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

Позже pacstrap скопирует этот файл в новую систему, так что это действительно стоит сделать.

Установка основных пакетов

Используйте скрипт pacstrap(8), чтобы установить пакет base, ядро Linux и прошивки часто встречающихся устройств:

# pacstrap -K /mnt base linux linux-firmware

Совет:

  • linux можно заменить на другой желаемый пакет ядра. Можно вообще не устанавливать ядро, если установка происходит в контейнере.
  • Можно пропустить установку пакета прошивок, если установка происходит в контейнере или виртуальной машине.

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

  • утилиты для управления файловыми системами в пользовательском пространстве, которые будут использоваться в системе,
  • утилиты для доступа к RAID- или LVM-разделам,
  • специфические прошивки других устройств, не включённые в linux-firmware (например, sof-firmware для некоторых звуковых карт),
  • ПО, необходимое для организации сети (например, менеджер сети или DHCP-клиент),
  • текстовый редактор,
  • пакеты для доступа к документации в man и info: man-db, man-pages и texinfo.

Чтобы установить другие пакеты или группы, добавьте их названия к команде pacstrap (разделяя их пробелом) или используйте pacman во время этапа #Chroot. Список пакетов, присутствующих в установочном образе, доступен на странице pkglist.x86_64.txt.

Настройка системы

Fstab

Сгенерируйте файл fstab (используйте ключ -U или -L, чтобы для идентификации разделов использовались UUID или метки, соответственно):

# genfstab -U /mnt >> /mnt/etc/fstab

После этого проверьте файл /mnt/etc/fstab и отредактируйте его в случае необходимости.

Chroot

Перейдите к корневому каталогу новой системы:

# arch-chroot /mnt

Часовой пояс

Задайте часовой пояс:

# ln -sf /usr/share/zoneinfo/Регион/Город /etc/localtime

Запустите hwclock(8), чтобы сгенерировать /etc/adjtime:

# hwclock --systohc

Эта команда предполагает, что аппаратные часы настроены в формате UTC. Для получения дополнительной информации смотрите раздел System time (Русский)#Стандарт времени.

Локализация

Отредактируйте файл /etc/locale.gen, раскомментировав en_US.UTF-8 UTF-8 и другие необходимые локали (например, ru_RU.UTF-8 UTF-8), после чего сгенерируйте их:

# locale-gen

Создайте файл locale.conf(5) и задайте переменной LANG необходимое значение:

/etc/locale.conf
LANG=ru_RU.UTF-8

Если вы меняли раскладку клавиатуры, сделайте это изменение постоянным в файле vconsole.conf(5). Также добавьте шрифт для консоли с поддержкой кириллицы:

/etc/vconsole.conf
KEYMAP=ru
FONT=cyr-sun16

Настройка сети

Создайте файл hostname:

/etc/hostname
моёимяхоста

Завершите настройку сети для вновь установленной среды. В частности, установите подходящее ПО для управления сетевым подключением.

Initramfs

Как правило, создание нового образа initramfs не требуется, поскольку pacstrap автоматически запускает mkinitcpio после установки пакета ядра.

Если вы используете LVM, шифрование системы или RAID, отредактируйте файл mkinitcpio.conf(5) и пересоздайте образ initramfs:

# mkinitcpio -P

Пароль суперпользователя

Установите пароль суперпользователя:

# passwd

Загрузчик

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

Перезагрузка

Выйдите из окружения chroot, набрав exit или нажав Ctrl+d.

Вы можете размонтировать все разделы с помощью команды umount -R /mnt, чтобы убедиться в том, что ни один из разделов не остался занят какой-либо программой. Если нужно, для поиска таких программ используйте fuser(1).

Теперь перезагрузите компьютер, набрав reboot: если какие-нибудь разделы остались смонтированными, systemd их размонтирует. Не забудьте извлечь установочный носитель. После загрузки войдите в систему в качестве суперпользователя.

После установки

Дальнейшие указания по настройке системы после установки (например, создание аккаунта обычного пользователя, настройка графического интерфейса, звука или тачпада) вы можете найти на странице Основные рекомендации.

Множество интересных и полезных программ вы найдете на странице Список приложений.

This document is a guide for installing Arch Linux using the live system booted from an installation medium made from an official installation image. The installation medium provides accessibility features which are described on the page Install Arch Linux with accessibility options. For alternative means of installation, see Category:Installation process.

Before installing, it would be advised to view the FAQ. For conventions used in this document, see Help:Reading. In particular, code examples may contain placeholders (formatted in italics) that must be replaced manually.

This guide is kept concise and you are advised to follow the instructions in the presented order per section. For more detailed instructions, see the respective ArchWiki articles or the various programs’ man pages, both linked from this guide. For interactive help, the IRC channel and the forums are also available.

Arch Linux should run on any x86_64-compatible machine with a minimum of 512 MiB RAM, though more memory is needed to boot the live system for installation.[1] A basic installation should take less than 2 GiB of disk space. As the installation process needs to retrieve packages from a remote repository, this guide assumes a working internet connection is available.

Pre-installation

Acquire an installation image

Visit the Download page and, depending on how you want to boot, acquire the ISO file or a netboot image, and the respective GnuPG signature.

Verify signature

It is recommended to verify the image signature before use, especially when downloading from an HTTP mirror, where downloads are generally prone to be intercepted to serve malicious images.

On a system with GnuPG installed, do this by downloading the ISO PGP signature (under Checksums in the page Download) to the ISO directory, and verifying it with:

$ gpg --keyserver-options auto-key-retrieve --verify archlinux-version-x86_64.iso.sig

Alternatively, from an existing Arch Linux installation run:

$ pacman-key -v archlinux-version-x86_64.iso.sig

Note:

  • The signature itself could be manipulated if it is downloaded from a mirror site, instead of from archlinux.org as above. In this case, ensure that the public key, which is used to decode the signature, is signed by another, trustworthy key. The gpg command will output the fingerprint of the public key.
  • Another method to verify the authenticity of the signature is to ensure that the public key’s fingerprint is identical to the key fingerprint of the Arch Linux developer who signed the ISO-file. See Wikipedia:Public-key cryptography for more information on the public-key process to authenticate keys.

Prepare an installation medium

The installation image can be supplied to the target machine via a USB flash drive, an optical disc or a network with PXE: follow the appropriate article to prepare yourself an installation medium from the chosen image.

Boot the live environment

Note: Arch Linux installation images do not support Secure Boot. You will need to disable Secure Boot to boot the installation medium. If desired, Secure Boot can be set up after completing the installation.

  1. Point the current boot device to the one which has the Arch Linux installation medium. Typically it is achieved by pressing a key during the POST phase, as indicated on the splash screen. Refer to your motherboard’s manual for details.
  2. When the installation medium’s boot loader menu appears, select Arch Linux install medium and press Enter to enter the installation environment.

    Tip:

    • The installation image uses GRUB for UEFI and syslinux for BIOS booting. Use respectively e or Tab to enter the boot parameters. See README.bootparams for a list.
    • A common example of manually defined boot parameter would be the font size. For better readability on HiDPI screens—when they are not already recognized as such—using fbcon=font:TER16x32 can help. See HiDPI#Linux console (tty) for a detailed explanation.
  3. You will be logged in on the first virtual console as the root user, and presented with a Zsh shell prompt.

To switch to a different console—for example, to view this guide with Lynx alongside the installation—use the Alt+arrow shortcut. To edit configuration files, mcedit(1), nano and vim are available. See pkglist.x86_64.txt for a list of the packages included in the installation medium.

Set the console keyboard layout and font

The default console keymap is US. Available layouts can be listed with:

# ls /usr/share/kbd/keymaps/**/*.map.gz

To set the keyboard layout, pass a corresponding file name to loadkeys(1), omitting path and file extension. For example, to set a German keyboard layout:

# loadkeys de-latin1

Console fonts are located in /usr/share/kbd/consolefonts/ and can likewise be set with setfont(8). For example, to use one of the largest fonts suitable for HiDPI screens, run:

# setfont ter-132b

Verify the boot mode

To verify the boot mode, list the efivars directory:

# ls /sys/firmware/efi/efivars

If the command shows the directory without error, then the system is booted in UEFI mode. If the directory does not exist, the system may be booted in BIOS (or CSM) mode. If the system did not boot in the mode you desired, refer to your motherboard’s manual.

Connect to the internet

To set up a network connection in the live environment, go through the following steps:

  • Ensure your network interface is listed and enabled, for example with ip-link(8):
    # ip link
  • For wireless and WWAN, make sure the card is not blocked with rfkill.
  • Connect to the network:
    • Ethernet—plug in the cable.
    • Wi-Fi—authenticate to the wireless network using iwctl.
    • Mobile broadband modem—connect to the mobile network with the mmcli utility.
  • Configure your network connection:
    • DHCP: dynamic IP address and DNS server assignment (provided by systemd-networkd and systemd-resolved) should work out of the box for Ethernet, WLAN, and WWAN network interfaces.
    • Static IP address: follow Network configuration#Static IP address.
  • The connection may be verified with ping:
    # ping archlinux.org

Update the system clock

In the live environment systemd-timesyncd is enabled by default and time will be synced automatically once a connection to the internet is established.

Use timedatectl(1) to ensure the system clock is accurate:

# timedatectl

Partition the disks

When recognized by the live system, disks are assigned to a block device such as /dev/sda, /dev/nvme0n1 or /dev/mmcblk0. To identify these devices, use lsblk or fdisk.

# fdisk -l

Results ending in rom, loop or airoot may be ignored.

Tip: Check that your NVMe drives and Advanced Format hard disk drives are using the optimal logical sector size before partitioning.

The following partitions are required for a chosen device:

  • One partition for the root directory /.
  • For booting in UEFI mode: an EFI system partition.

If you want to create any stacked block devices for LVM, system encryption or RAID, do it now.

Use fdisk or parted to modify partition tables. For example:

# fdisk /dev/the_disk_to_be_partitioned

Note:

  • If the disk does not show up, make sure the disk controller is not in RAID mode.
  • If the disk from which you want to boot already has an EFI system partition, do not create another one, but use the existing partition instead.
  • Swap space can be set on a swap file for file systems supporting it.

Example layouts

UEFI with GPT

Mount point Partition Partition type Suggested size
/mnt/boot1 /dev/efi_system_partition EFI system partition At least 300 MiB. If multiple kernels will be installed, then no less than 1 GiB.
[SWAP] /dev/swap_partition Linux swap More than 512 MiB
/mnt /dev/root_partition Linux x86-64 root (/) Remainder of the device
  1. Other mount points, such as /mnt/efi, are possible, provided that the used boot loader is capable of loading the kernel and initramfs images from the root volume. See the warning in Arch boot process#Boot loader.
BIOS with MBR

Mount point Partition Partition type Suggested size
[SWAP] /dev/swap_partition Linux swap More than 512 MiB
/mnt /dev/root_partition Linux Remainder of the device

See also Partitioning#Example layouts.

Format the partitions

Once the partitions have been created, each newly created partition must be formatted with an appropriate file system. See File systems#Create a file system for details.

For example, to create an Ext4 file system on /dev/root_partition, run:

# mkfs.ext4 /dev/root_partition

If you created a partition for swap, initialize it with mkswap(8):

# mkswap /dev/swap_partition

Note: For stacked block devices replace /dev/*_partition with the appropriate block device path.

If you created an EFI system partition, format it to FAT32 using mkfs.fat(8).

Warning: Only format the EFI system partition if you created it during the partitioning step. If there already was an EFI system partition on disk beforehand, reformatting it can destroy the boot loaders of other installed operating systems.

# mkfs.fat -F 32 /dev/efi_system_partition

Mount the file systems

Mount the root volume to /mnt. For example, if the root volume is /dev/root_partition:

# mount /dev/root_partition /mnt

Create any remaining mount points (such as /mnt/boot) and mount the volumes in their corresponding hierarchical order.

Tip: Run mount(8) with the --mkdir option to create the specified mount point. Alternatively, create it using mkdir(1) beforehand.

For UEFI systems, mount the EFI system partition:

# mount --mkdir /dev/efi_system_partition /mnt/boot

If you created a swap volume, enable it with swapon(8):

# swapon /dev/swap_partition

genfstab(8) will later detect mounted file systems and swap space.

Installation

Select the mirrors

Packages to be installed must be downloaded from mirror servers, which are defined in /etc/pacman.d/mirrorlist. On the live system, after connecting to the internet, reflector updates the mirror list by choosing 20 most recently synchronized HTTPS mirrors and sorting them by download rate.

The higher a mirror is placed in the list, the more priority it is given when downloading a package. You may want to inspect the file to see if it is satisfactory. If it is not, edit the file accordingly, and move the geographically closest mirrors to the top of the list, although other criteria should be taken into account.

This file will later be copied to the new system by pacstrap, so it is worth getting right.

Install essential packages

Note: No software or configuration (except for /etc/pacman.d/mirrorlist) get carried over from the live environment to the installed system.

Use the pacstrap(8) script to install the base package, Linux kernel and firmware for common hardware:

# pacstrap -K /mnt base linux linux-firmware

Tip:

  • You can substitute linux for a kernel package of your choice, or you could omit it entirely when installing in a container.
  • You could omit the installation of the firmware package when installing in a virtual machine or container.

The base package does not include all tools from the live installation, so installing more packages may be necessary for a fully functional base system. To install other packages or package groups, append the names to the pacstrap command above (space separated) or use pacman to install them while chrooted into the new system. In particular, consider installing:

  • userspace utilities for the management of file systems that will be used on the system,
  • utilities for accessing RAID or LVM partitions,
  • specific firmware for other devices not included in linux-firmware (e.g. sof-firmware for sound cards),
  • software necessary for networking (e.g. a network manager or a standalone DHCP client, authentication software for Wi-Fi, ModemManager for mobile broadband connections),
  • a text editor,
  • packages for accessing documentation in man and info pages: man-db, man-pages and texinfo.

For comparison, packages available in the live system can be found in pkglist.x86_64.txt.

Configure the system

Fstab

Generate an fstab file (use -U or -L to define by UUID or labels, respectively):

# genfstab -U /mnt >> /mnt/etc/fstab

Check the resulting /mnt/etc/fstab file, and edit it in case of errors.

Chroot

Change root into the new system:

# arch-chroot /mnt

Time zone

Set the time zone:

# ln -sf /usr/share/zoneinfo/Region/City /etc/localtime

Run hwclock(8) to generate /etc/adjtime:

# hwclock --systohc

This command assumes the hardware clock is set to UTC. See System time#Time standard for details.

Localization

Edit /etc/locale.gen and uncomment en_US.UTF-8 UTF-8 and other needed locales. Generate the locales by running:

# locale-gen

Create the locale.conf(5) file, and set the LANG variable accordingly:

/etc/locale.conf
LANG=en_US.UTF-8

If you set the console keyboard layout, make the changes persistent in vconsole.conf(5):

/etc/vconsole.conf
KEYMAP=de-latin1

Network configuration

Create the hostname file:

/etc/hostname
myhostname

Complete the network configuration for the newly installed environment. That may include installing suitable network management software.

Initramfs

Creating a new initramfs is usually not required, because mkinitcpio was run on installation of the kernel package with pacstrap.

For LVM, system encryption or RAID, modify mkinitcpio.conf(5) and recreate the initramfs image:

# mkinitcpio -P

Root password

Set the root password:

# passwd

Boot loader

Choose and install a Linux-capable boot loader. If you have an Intel or AMD CPU, enable microcode updates in addition.

Reboot

Exit the chroot environment by typing exit or pressing Ctrl+d.

Optionally manually unmount all the partitions with umount -R /mnt: this allows noticing any «busy» partitions, and finding the cause with fuser(1).

Finally, restart the machine by typing reboot: any partitions still mounted will be automatically unmounted by systemd. Remember to remove the installation medium and then login into the new system with the root account.

Post-installation

See General recommendations for system management directions and post-installation tutorials (like creating unprivileged user accounts, setting up a graphical user interface, sound or a touchpad).

For a list of applications that may be of interest, see List of applications.

Время на прочтение
4 мин

Количество просмотров 149K

Как установить Arch без боли??

Предисловие

Слышал, что некоторые считают Arch сложным в установке. Отчасти они правы, но для любого человека, который способен разобраться в установке и настройке linux, установка Arch довольно проста. Также это самый гибкий дистрибутив, поэтому настроить под себя его получится лучше других дистрибутивов.

Данный гайд является сборной солянкой из всех гайдов, что я прочитал (как русскоязычные, так и иноязычные). Его цель просто и без лишней технической информации показать пошаговую установку Arch и сделать это на русском языке. Главное, что статья написана от непонимающего для непонимающих. Заранее скажу, что некоторые скрины будут уже с установленного Arch, но это никак не меняет работу команд и то, что вы увидите при их использование.

Итак, начнём с простого.

Идём на сайт и качаём ISO-файл:

Там ищем зеркало(скорее всего русское) и скачиваем образ:

Для упрощения дальнейшей жизни лучше скачать Etcher, прямо на сайте есть довольно понятная инструкция в картинках, так что справятся все.

 Установка

// начну с настройки VirtualBox, если вы используете её, то выполните следующие действия

1.Идём в настройки машины:

2.Во вкладке система ставим галочку около пункта »Включить EFI»:

3.Далее идём во вкладку носители, там добавляем контроллер IDE и выбираем наш дистрибутив

Далее установка будет для всех одинакова.

Начинаем с запуска

Выбираем первую строку и жмём Enter

Проверим соединение с интернетом:

Это нужно, потому что Arch требует интернет для своей установки.

Такой командой можно проверить своё соединение и увидеть время ответа сайта.

ping -c 3  google.com

Если вы используете wifi на своём ПК, то используйте утилиту :

wifi-menu

Вы увидите примерно это:

Разделы диска

Для того, чтоб разбить наш диск на разделы, можно сначала узнать какие диски подключены. Скорее всего у вас будет USB флешка и HDDSSD вашего ПК.

Команда для просмотра разделов (понадобится нам ещё много раз):

lsblk

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

fdisk -l

Время размечать наш диск. Используем команду cfdisk для этого и выбираем gpt формат :

cfdisk /dev/sda

Bажно! если во время использования команды lsblk и fdisk вы увидели что sda является не тем диском, что нужен вам, то вы дописываете в конец название другого диска, например sdb.

Используя стрелочки создаём 3 раздела на диске:

  • /dev/sda1 # размером 1G места под UEFI
  • /dev/sda2 # размером примерно 10-15 GB под root
  • /dev/sda3 # всё оставшееся место под директорию home

PS: Если вы решили переделать разметку диска, то через эту утилиту можно и удалять разделы

Для проверки используем lsblk снова. Если всё норм, что /dev/sda будет содежать в себе 3 раздела.


Далее форматируем наши разделы.

  1. Форматируем тот раздел, который мы выделили под UEFi

    mkfs.fat -F32 /dev/sda1

  2. Раздел root

    mkfs.ext4 /dev/sda2

  3. Раздел home

    mkfs.ext4 /dev/sda3

Монтируем root и создаём папку home:

mount /dev/sda2 /mnt
mkdir /mnt/home
mount /dev/sda3 /mnt/home

И снова lsblk для проверки

Установка

Начинается самая долгая часть, потому что нужно будет много скачать. Устанавливаем все основные пакеты, а также nano, чтоб редачить файлы системы. Если вдруг вы знакомы с  vim можете скачать и его (дописать в конец).

pacstrap -i /mnt base linux linux-firmware sudo nano

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

Создадим  fstab файл

genfstab -U -p /mnt >> /mnt/etc/fstab

 Настраиваем установленную систему

Chroot

Chroot (change root) нужен нам, чтобы мы могли сменить  root пользователя (как и сказано в названии команды).

arch-chroot /mnt /bin/bash

Настройка файла локали

Для начала идём в файл локали, чтоб настроить язык

nano /etc/locale.gen

Находим там #en_US.UTF-8 и стираем #, с русским языком так же. PS: можно использовать Ctrl + W для поиска языка в файле.

Чтобы всё сохранить Ctrl + O, затем Enter и Ctrl + X, затем Enter

Далее пишем команды, которые сгенерируют локаль и создаём locale.conf с нужными настройками языка.

locale-gen
echo "LANG=en_US.UTF-8" > /etc/locale.conf

Настраиваем временную зону

ln -sf /usr/share/zoneinfo/

Далее жмём 2 раза на Tab и видим список регионов, после городов.

В моём случае было так:

ln -sf /usr/share/zoneinfo/Europe/Kaliningrad /etc/localtime

Задаём время

Тут 2 команды. Одна ставит время для системы, а другая его показывает.

hwclock --systohc --utc
date

Имя хоста и адрес

Я решил назвать ПК ArchMe, поэтому используем следующую команду:

echo ArchMe > /etc/hostname

Далее идём в файл localhosts и записываем ip. Если у вас ip статический, используйте свой.

nano /etc/hosts
127.0.1.1 localhost.localdomain ArchMe

Сетевой менеджер

Качаем и включаем.

pacman -S networkmanager
systemctl enable NetworkManager 

Установка GRUB

Для начала сменим пароль root пользователя :

passwd

GRUB — это загрузчик, который нужен, чтоб запускать нашу установленную систему (в режиме EFI). Далее будет куча команд, которые нужно выполнить.

pacman -S grub efibootmgr
mkdir /boot/efi
mount /dev/sda1 /boot/efi
lsblk # для проверки всё ли норм смонтировано 
grub-install --target=x86_64-efi --bootloader-id=GRUB --efi-directory=/boot/efi --removable
grub-mkconfig -o /boot/grub/grub.cfg

Перезагрузка

Чтобы без потерь перезагрузить нашу систему используем эти команды:

exit
umount -R /mnt
reboot

После перезагрузки вы увидите следующее. Если это так, то наш GRUB установился правильно

Входим в root аккаунт и создаём  swapfile (что-то вроде доп оперативки) и задаём ему размер как у вашей ОЗУ

fallocate -l 3G /swapfile

Далее выполняем следующие команды:

chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
echo '/swapfile none swap sw 0 0' >> /etc/fstab

И проверяем, работает ли swap:

free -m

Добавим пользователя и окружение

useradd -m -g users -G wheel -s /bin/bash username
passwd username

username замените на то имя, что хотите вы)

Также нужно дать ему права суперюзера:

EDITOR=nano visudo

там ищем  и убираем #, а дальше Ctrl + O, затем Enter и Ctrl + X, затем Enter

# %wheel ALL=(ALL) ALL

Дрова

pacman -S pulseaudio pulseaudio-alsa xorg xorg-xinit xorg-server

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

Окружение

Вначале покажу как поставить довольно простое — XFCE

pacman -S xfce4 lightdm lightdm-gtk-greeter
echo "exec startxfce4" > ~/.xinitrc
systemctl enable lightdm

И моё любимое  i3, там выбираем пакеты 2 4 5. Возможно вы увидите квадраты вместо символов, но это нормально, вам просто нужно будет скачать шрифт dejavu (pacman -S ttf-dejavu). Cписок горячих клавиш можно посмотреть  тут

echo "exec i3"  > ~/.xinitrc
sudo pacman -S i3

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

Для запуска вашего окружения используйте

startx

Table of Contents

  • Table of Contents
  • Установка Arch Linux
    • Arch Linux
    • Создание образа
    • Изменяем приоритет загрузки в BIOS/UEFI
    • Начало установки
    • Настройка сети
    • Выбор файловой системы
    • Размечаем диск
    • Вариант 1: LVM
    • Вариант 2: Btrfs
    • Устанавливаем ядро
    • Генерируем fstab
    • arch-chroot
    • Настраиваем дату и локаль
    • Прописываем хосты
    • Initramfs
    • Ставим пакеты
    • Пользователи
    • Установка grub
    • Ставим Gnome
    • Завершение установки
  • man & help
  • Типы файлов в выводе ls и других стандартных команд
  • Пакетные менеджеры
  • Нужные пакеты
  • Заменяем ядро на стабильное
  • Масштабировавние 150% как в Windows
  • Расширения для Gnome
  • Пользовательские сочетания клавиш
  • Запуск исполняемых файлов по двойному клику в Nautilus
  • Добавляем новые действия в контекстное Nautilus
  • Шаблоны файлов
  • Гибернация
  • RAID
  • Права
  • Монтирование
  • Добавляем путь в PATH
  • bin в домашнем каталоге
  • Монтируем Windows разделы
  • Шрифты
  • Emoji
  • Спецсимволы
  • Сетевые интерфесы
  • Блокируем сайты с рекламой через hosts
  • Информация о железе
  • Редактирование DConf
  • ZSH
    • Установка ZSH
    • Oh My Zsh
    • Темы Oh My Zsh!
      • Bullet Train for oh-my-zsh
      • Jovial
      • Powerlevel10k
    • Подробнее про ZSH
  • Разноцветный cat
  • Цветовые схемы для терминала
  • Бекап системы
  • asdf-vm
  • NVM
  • Настройка Docker
  • Настройка Visual Code
  • LVM
  • Btrfs
  • Snapper
  • Timeshift
  • Логи
  • Установка и настройка Postgres
  • Мониторинг процессов
  • systemd
  • Git
  • Работаем с github через ssh
  • Tor Service
  • Менеджер паролей pass
  • Частые проблемы
    • Система не грузится дальше rootfs
    • Grub Rescue
    • Случайно нажали Ctrl + Alt + F* и экран стал темным
    • Что делать, если каталоги открываются в VSCode?
    • Enter password to unlock your login keyring
  • Справка по командам и т.д.
    • Cheat.sh
    • Marker
    • TLDR
  • Шпаргалка по командам Shell
  • i3: Введение
  • i3: Установка и настройка
  • XTerm
  • Termite: горячие клавиши
  • Termite: цветовые схемы
  • i3: заставка lockscreen
  • i3: сохранение/восстановление рабочего пространства

Arch Linux

Arch Linux ‒ это один из немногих дистрибутивов Linux, использующих модель роллинг-релизов. Это означает, что в нем доступны самые последние версии пакетов. Это одновременно является его как преимуществом так и недостатком. Пересесть на него меня заставила необходимость: мое компьютерное железо (процессор ryzen 5 2600 и видеоадаптер rx 590) оказались не совместимы с версией Linux Kernel младше 4.20.

image

На самом деле все не так плохо, но неприятные инциденты имеют место хотя и очень редко.

Создание образа

Качаем образ и записываем его с помощью команды:

$ sudo dd if=/path/to/iso of=/dev/sdX bs=8M status=progress; sync

Где sdX – имя нашего USB устройства. Перегружаемся после удачного завершения операции.

В Windows для создания загрузочной флешки можно использовать Rufus.

image

Изменяем приоритет загрузки в BIOS/UEFI

При загрузке системы нажимаем F2 или Del (зависит от производителя материнской платы). Во вкладке BIOS в приоритете загрузки делаем первым наше USB-устройство. Нажимаем F10 и сохраняем настройки.

Начало установки

Инструкцию по установке Arch Linux можно посмотреть так:

Небольшой лайфхак: во время установки можно переключаться между терминалами с помощью Ctrl+Alt+F1..6. Если мы нажмем Ctrl+Alt+F2 откроется второй терминал (по-умолчанию мы работаем в первом) и потребуется ввести пароль root, во втором терминале мы можем открыть инструкцию и периодически подсматривать ее, переключаясь между терминалами.

Настройка сети

При подключении от кабеля ничего настраивать не надо. Настройка wifi требует ввода пары команд:

rfkill unblock wifi
wifi-menu

Следует отметить, что не все usb wifi адаптеры гараниторованно поддерживаются. Например, у меня не захотел работать dexp wfa 301, а вот с tp-link все ок.

Проверить соединение можно с помощью команды ping:

$ ping -c 3 ya.ru
PING ya.ru (87.250.250.242) 56(84) bytes of data.
64 bytes from ya.ru (87.250.250.242): icmp_seq=1 ttl=53 time=12.1 ms
64 bytes from ya.ru (87.250.250.242): icmp_seq=2 ttl=53 time=12.1 ms
64 bytes from ya.ru (87.250.250.242): icmp_seq=3 ttl=53 time=12.1 ms

--- ya.ru ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 5ms
rtt min/avg/max/mdev = 12.137/12.139/12.141/0.127 ms

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

Самыми удобными являются три варианта: LVM+ext4 либо Btrfs, либо Btrfs под LVM.

Теперь нужно разметить раздел по LVM. Касательно LVM: единственное удобство в нем для меня – это возможность динамически менять размер разделов. Самая частая проблема, которая у меня была раньше – это то, что я не угадывал размер для корня. Мы можем добавлять в группу другие разделы (не обязательно на одном устройстве) и устройства. Нет ограничений как для обычных разделов, когда не возможно расширить раздел за счет предыдущего, нам вообще об этом не нужно заботиться. В LVM у нас есть группы разделов и логическите разделы. У логических разделов свои файловые системы. Увеличение размера логического раздела в отличии от уменьшения размонтирования не требует. resize2fs в LVM работает заметно быстрее.

Файловая система Btrfs может размещаться на одном и более устройствах/разделах. Устройства и разделы можно как добавлять так и удалять после создания. У нас тут нет групп и логических разделов со своими файловыми системами. У нас есть только подразделы с динамическим размером, что удобно. Так же мы можем ограничить размер подраздела.

LVM и Btrfs имеют механизм снапшотов, которые позволяют сохранять состояние системы.

Размечаем диск

Для начала посмотрим все доступные устройства:

Создадим новый раздел:

# fdisk /dev/nvme0n1
# Более удобная утилита чем fdisk, в ней можно выбирать все стрелочками
cfdisk /dev/nvme0n1
# При разметке swap размещайте после home, т.е. самым последним на случай, если потребуется увеличить его размер

Если есть раздел с Windows сделайте от него отступ 1-2 MB, т.к. Windows выходит за установленные лимиты и портит соседние разделы.

Если не установлен Windows:

Создаем раздел в FAT-32 размером 300-1000 Мб, а затем форматируем его:

mkfs.fat -F32 /dev/nvme0n1p1

В дальнейших примерах предполагается, что у нас установлена Windows, которая занимает 4 раздела: recovery, efi, reserved, Windows. Поэтому в примерах новый раздел nvme0n1p5.

Вариант 1: LVM

# Создадим группу на разделе без файловой системы
vgcreate linux /dev/nvme0n1p5
# Теперь создадим в ней логические разделы:
lvcreate -L 30G linux -n root
lvcreate -L 20G linux -n home
# Можно для раздела отдать все оставшееся место
lvcreate -L +100%FREE linux -n home
mkfs.ext4 /dev/linux/root
mkfs.ext4 /dev/linux/home
mount /dev/linux/root /mnt
mkdir /mnt/home
mount /dev/linux/home /mnt/home
# Создаем файл подкачки. Не нужно верить дурачкам: он нужен всегда. Без него система будет лагать
fallocate -l 2G /mnt/swapfile
# Если хотим использовать гибернацию, то размер файла подкачки должен составлять около 2/5 от размера оперативной памяти на современном компьютере, в идеале он должен быть ему равен либо даже больше
# fallocate -l `awk '/Mem:/ {print $2}' <(free -m)`M /mnt/swapfile
chmod 600 /mnt/swapfile
mkswap /mnt/swapfile
swapon /mnt/swapfile
mkdir -p /mnt/boot/efi
mount /dev/nvme0n1p2 /mnt/boot/efi

Вариант 2: Btrfs

# Сначала монтируем раздел
mount /dev/nvme0n1p5 /mnt
# Потом создаем на нем подразделы
btrfs subvolume create /mnt/@
btrfs subvolume create /mnt/@home
# Теперь мы демонтируем устройство
umount /mnt
# и монтируем созданные подразделы
mount -o noatime,compress=lzo,space_cache,subvol=@ /dev/nvme0n1p5 /mnt
mkdir /mnt/home
mount -o noatime,compress=lzo,space_cache,subvol=@home /dev/nvme0n1p5 /mnt/home
# Файл подкачки нужно создавать так
# И что очень важно: поддержка файлов подкачки в Btrfs доступна в версией ядра linux, начниная с 5.0.0
truncate -s 0 /mnt/swapfile
chattr +C /mnt/swapfile
btrfs property set /mnt/swapfile compression none
# fallocate -l 2G /mnt/swapfile
# С fallocate могут возникнуть проблемы
dd if=/dev/zero of=/mnt/swapfile count=2000 bs=1M
chmod 600 /mnt/swapfile
mkswap /mnt/swapfile
swapon /mnt/swapfile
mkdir -p /mnt/boot/efi
mount /dev/nvme0n1p2 /mnt/boot/efi

Эта инструкция лучше

Устанавливаем ядро

pacstrap /mnt base base-devel

base-devel содержит набор утилит для компиляции, позже пригодится

Генерируем fstab

genfstab -U /mnt >> /mnt/etc/fstab

arch-chroot

При использовании LVM нужно выполнить чуть больше действий:

# Предотвращаем ошибки lvm:
#   WARNING: Failed to connect lvmetad...
#   WARNING: Device /dev/nvme0n1 not initialized in udev database...
mkdir /mnt/hostlvm
mount --bind /run/lvm /mnt/hostlvm
arch-chroot /mnt
ln -s /run/lvm /hostlvm

Настраиваем дату и локаль

ln -sf /usr/share/zoneinfo/Europe/Moscow /etc/localtime
hwclock --systohc

Далее:

Раскоментируем:

Генерируем локаль:

locale-gen
echo "LANG=en_US.UTF-8" > /etc/locale.conf

Если пропустить этот шаг, то не будет запускаться терминал.

Прописываем хосты

echo "sergey-pc" > /etc/hostname

Добавляем в файл такие строки:

127.0.0.1 localhost
::1 localhost
127.0.1.1 sergey-pc.localdomain sergey-pc

Initramfs

mkinitcpio это Bash скрипт используемый для создания начального загрузочного диска системы. Из mkinitcpio man page:

⚠ Это обязательный шаг даже, если не используется LVM, а так же при изменение пути до корня

При использовании LVM нужно отредактировать /etc/mkinitcpio.conf и модифицировать список HOOKS, добавив lvm2 ДО ЗНАЧЕНИЯ filesystems:

HOOKS=(base udev autodetect modconf block lvm2 filesystems keyboard fsck)

Генерация:

Ставим пакеты

Эти пакеты понадобятся далее:

pacman -S linux linux-headers linux-firmware btrfs-progs sudo grub efibootmgr ntfs-3g os-prober alsa-utils xf86-video-ati xorg xorg-server

linux больше в base не входит, linux-headers для любителей покомпилировать, linux-firmware содержит набор драйверов.

btrfs-progs нужен только, если используется файловая система btrfs.

xf86-video-ati – свободный драйвер для видеокарт AMD. xorg и xorg-server можно не ставить, они являются зависимостями пакета gnome.

Пользователи

Задаем пароль для супер-пользователя:

Создаем пользователя:

useradd -m -g users -G wheel -s /bin/bash sergey

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

passwd sergey
chage -d 0 sergey

Пароль для пользователя можно ставить 1, так как при логине придется его сменит.

Теперь в файле /etc/sudoers нужно раскоментировать строку:

%wheel ALL=(ALL:ALL) ALL

Установка grub

grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id="Arch Linux"

Чтобы отключить автоматическую загрузку Linux, редактируем дефолтный конфиг груба:

Меняем GRUB_TIMEOUT:

GRUB_TIMEOUT=-1

Затем генерируем grub:

grub-mkconfig -o /boot/grub/grub.cfg

Ставим Gnome

pacman -S gnome
# Включаем Gnome Display Manager
systemctl enable gdm

Вместо Gnome можно попробовать тайловый менеджер i3.

Завершение установки

Включаем NetworkManager для автоматического подключения к сети:

systemctl enable NetworkManager

Надо еще настроить звук:

# Сохраним на всякий случай состояние
alsactl store
# Для автоматического сохранения/восстановления значения громкости звука:
systemctl enable alsa-restore

Теперь можно выходить и перегружаться:


man & help

$ man [ <section> ] <page>

# Section	Description
# 1	General Commands
# 2	System Calls
# 3	Library functions, covering in particular the C standard library
# 4	Special files (usually devices, those found in /dev) and drivers
# 5	File formats and conventions
# 6	Games and screensavers
# 7	Miscellanea
# 8	System administration commands and daemons

# Узнать где хранятся страницы манулов можно так
$ manpath
/usr/local/man:/usr/local/share/man:/usr/share/man

$ man -w printf
/usr/share/man/man1/printf.1.gz

# Поиск страниц по ключевому слову
$ man -k printf

# Смотрим все страницы
$ man -f printf
printf (1)           - format and print data
printf (1p)          - write formatted output
printf (3)           - formatted output conversion
printf (3p)          - print formatted output

# Выбираем конкретную
$ man 1p printf

# Краткая справка по функции
$ command -h
$ command --help

Типы файлов в выводе ls и других стандартных команд

There is only 1 command you need to know, which will help you to identify and categorize all the seven different file types found on the Linux system.

Here is an example output of the above command.

 $ ls -ld /etc/services
-rw-r--r-- 1 root root 19281 Feb 14  2012 /etc/services

ls command will show the file type as an encoded symbol found as the first character of the file permission part. In this case it is «-«, which means «regular file». It is important to point out that Linux file types are not to be mistaken with file extensions. Let us have a look at a short summary of all the seven different types of Linux file types and ls command identifiers:

- : regular file
d : directory
c : character device file
b : block device file
s : local socket file
p : named pipe
l : symbolic link

Пакетные менеджеры

Пакетным менеджером по-умолчанию для Arch Linux является pacman. Для подсветки вывода pacman в /etc/pacman.conf нужно раскомментировать Color. Пользовательским репозиторием является AUR. Пакеты из него можно использовать только на свой страх и риск. Чтобы не собирать пакеты из него ручками можно поставить yay:

sudo pacman -S git
cd /tmp
git clone https://aur.archlinux.org/yay.git
cd yay
makepkg -si

Пакеты всегда нужно ставить из репозиториев. Смысла собирать их из исходников нет, так как в AUR и так самые последние версии. Так будет меньше хлама оставаться в системе после их удаления.

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

Синтаксис команды Yay аналогичен pacman. Так что будет полезным почитать справку по pacman.

Ссылки:

  • Сравнеие пакетных менеджеров.

Нужные пакеты

Это список необходимых для меня пакетов:

yay -Sy linux-headers  # нужны для компиляции некоторых программ
  wget  # позволяет выполнять HTTP-запросы, скачивать файлы
  curl  # делает то же самое, что и предыдущий
  adobe-source-code-pro-fonts  # шрифт для терминала, нужен для темы Oh My Zsh! agnoster
  ttf-droid  # шрифт по-умолчанию для VScode
   # шрифты по-умолчанию для Chrome
   # consolas-font 
   # ttf-ms-fonts 
  arc-gtk-theme-git  # тема для интерфейса
  apache  # самый популярный веб-сервер
  apache-tools  # содержит ab, нагрузочный клиент
   # blender  # самый простой 3D-редактор
  dconf-editor  # все настройки gnome в одном месте
  dmraid  # утилита для работы с raid-массивами дисков
  docker-compose  # содержит docker и docker compose
  exfat-utils  # добавляет поддержку файловой системы exfat
  firefox  # один из лучших браузеров, единственный конкурент Chrome и единственный популярный non-chromium браузер
  flat-remix-git  # тема с иконками
   # gimp  # скромненький аналог Photoshop
  gnome-panel  # я ставил только чтобы ярлыки из GUI создавать
  google-chrome  # лучший браузер, противники проприетарщины предпочитают chromium
  chrome-gnome-shell  # позволяет устанавливать расширения для Gnome
  gparted  # графическая оболочка для разметки дисков
  htop  # показывает запущенные процессы, загрузку cpu и потребление памяти
   # inkscape  # векторный графический редактор
   # mariadb  # свободная реализация самой популярной СУБД MySQL
  mc  # аналог виндового Far + mcedit, замена nano
   # mongodb-bin  # лучшая NoSQL база данных
  net-tools  # содержит netstat
  neofetch  # выводит в консоль информацию о системе
  nginx  # самый быстрый веб-сервер
  ntfs-3g  # добавляет поддержку файловой системы ntfs
   # nvm  # менеджер версий для Node.js
   # postgresql  # лучшая SQL база данных
   # phpenv  # менеджер версий для PHP
   # pyenv  # менеджер версий для Python
  asdf-vm  # Заменяет собой все выше перечисленные менеджеры версий + умеет управлять базами
   # pgadmin4  # админка для Postgres
   # pgmodeler  # визуальный редактор для моделирования в Postgres
   # redis  # СУБД в оперативной памяти, используемая для межпроцессового взаимодействия
  smartmontools  # утилита для проверки состояния SSD
  telegram-desktop-bin  # лучший мессенджер
  texmaker  # редактор LaTex, генерирует PDF
  tor  # сервис, который можно использовать для подключения к сети Tor
  torsocks  # утилита torify, которая заставляет другие программы работать через Tor
  transmission-qt  # торрент-клиент
  thunderbird  # email-клиент
  virtualbox  # виртуальная машина, позволяет запускать Windows и Linux
  visual-studio-code-bin  # лучший бесплатный текстовый редактор
  vlc  # видеоплеер
  websocat-bin  # утилита для тестированя вебсокетов
  woeusb  # создание загрузочных флешек с Windows
  xclip  # копирование файла в буффер обмена из консоли
  seahorse  # Приложение для управления паролями, а так же PGP и SSH ключами
  baobab  # Приложения для мониторинга дисков
  jq  # Утилита для работы с JSON
  pv  # получает на вход поток и перенаправляет его, показывая статистику
  httpie  # лучшая замена curl с подсветкой вывода
  tor-browser  # Tor браузер
  

Заменяем ядро на стабильное

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

yay -S linux-lts linux-headers-lts
yay -R linux linux-headers
mkinitcpio -p linux

Масштабировавние 150% как в Windows

По-умолчанию в Gnome масштабирование кратно 100. Чтобы добавить варианты масштабирования 125% и 150% нужно выполнить в терминале:

gsettings set org.gnome.mutter experimental-features "['scale-monitor-framebuffer']"

Отключение:

gsettings reset org.gnome.mutter experimental-features

Расширения для Gnome

Устанавливаем расширение для Chrome.

image

Управление расширениями осуществляется через Tweaks.

image

Расширения для установки:

Название Описание
Dash to Dock. Выезжающий Dash — панель с избранными приложениями
Desktop Icons Иконки на рабочем столе
ShellTile Тайловый менеджер
Log Out Button Добавляет кнопку, которая выполняет выход из системы

Пользовательские сочетания клавиш

В Settings → Devices → Keyboard добавляем сочетания клавиш:

  • Ctrl + Alt + T для запуска терминала (gnome-terminal);
  • Ctrl + Alt + V для запуска Visual Code (code).

image

Запуск исполняемых файлов по двойному клику в Nautilus

Заставляем Nautilus выполнять исполняемые файлы вместо открытия их в текстовом редакторе. Нужно нажать на три точки, а потом выбрать Preferences:

image

Добавляем новые действия в контекстное Nautilus

$ yay -S filemanager-actions

У программы есть интерфейс, который позволяет добавлять свои команды. Существуют два плейсхолдера: %d для текущего каталога и %f для файла.

To install nautilus-action on Ubuntu, run simply this command via the Terminal:

sudo apt-get install nautilus-actions
(or equivalant packet manager as yum or pacman)

After the installation is complete, let’s now see a quick example of how to add an extra action to the right-click menu with nautilus-actions.

The example consists of adding to the right-click menu the «Edit With Gimp» action to edit, for example, image files using The Gimp (Image Editor).

_Using the dash search «nautilus-actions» and click Nautilus-Actions Configuration.

_Under the Action tab, fill the following fields:

Context label: The text that will be displayed in the right-click menu, in our example, it’s «Edit With Gimp»
Icon: This option allows to select an icon for your action (optional)
_Open now the Command tab and fill in the following fields:

Label: Enter any label of your choice for your action.
Path: Enter the path to the program you want to use using the Browse button. For our example, we will simply type «gimp».
Parameters: Click the Legend button to get suggested parameters. In our example, we will use the %f parameter to be able to edit image files with The Gimp.
_Log out the current session and log on again, or simply restart Nautilus with these commands from the Terminal:

nautilus -q
nautilus

Страница проекта.

Шаблоны файлов

Чтобы в Nautilus в контекстном меню отображался пункт New Document, нужно в ~/Templaytes создать шаблоны файлов:

touch ~/Templates/{Empty Document,Text Document.txt,README.md,pyfile.py}

Гибернация

Режим гибернациии от режима сна отличается тем, что в первом случае содержимое оперативной памяти сохраняется на жесткий диск и питание полностью отключается, во втором — питание подается только на оперативку. Чем хороша гибернация? — Например, мы работаем в Linux, вошли в режим гибернации, а затем загрузились в Windows и играем. Когда мы в следующий раз загрузимся в Linux, то увидим все то, что было перед выключением. Прекрасно?! Но часто ли такое нужно?

При переходе в режим гибернации делается дамп используемой оперативной памяти на диск. Размер файла/раздела подкачки для этих целей советуют делать не менее 2/5 от объема RAM на современных компьютерах. Так же можно применять сжатие при дампе. Про гибернацию лучше почитать здесь.

Режим гибернации по-умолчанию отключен. Чтобы его включить для начала нужно узнать UUID раздела, где расположен своп, а так же смещение своп-файла относительно начала раздела:

$ lsblk `df /swapfile | awk '/^/dev/ {print $1}'` -no UUID
217df373-d154-4f2e-9497-fcac21709729
$ sudo filefrag -v /swapfile | awk 'NR == 4 {print $5}' | cut -d ':' -f 1
1423360

screenshot from 2019-02-23 02-12-34

В /etc/default/grub прописать:

GRUB_CMDLINE_LINUX_DEFAULT="quiet resume=UUID=217df373-d154-4f2e-9497-fcac21709729 resume_offset=1423360"

resume_offset нужен только для файла. Для дисков и разделов вместо UUID можно указывать /dev/sda3 или /dev/mapper/linux-swap.

Теперь нужно изменить /etc/mkinitcpio.conf:

# resume должен следовать после filesystems
HOOKS=(...filesystems resume...)

Обновляем grub и генерируем initramfs:

sudo grub-mkconfig -o /boot/grub/grub.cfg
sudo mkinitcpio -p linux

Сам переход в режим гибернации выглядит так:

Чтобы появилась кнопка для перехода в режим гибернации ставим расширение.

image
image

RAID

Аппаратный RAID

В Linux RAID на аппаратном уровне называют FakeRAID. Для работы с FakeRAID используется пакет dmraid.

Редактируем конфиг mkinitcpio:

sudo nano /etc/mkinitcpio.conf

В хуки добавляем dmraid:

HOOKS=(base udev autodetect modconf block lvm2 dmraid filesystems keyboard fsck)

И генерируем mkinitcpio:

На моей материнке с чипсетом b450 с апаратным RAID из Linux работать нельзя: нет драйвера.

Программный Windows RAID

Этот раздел можно было бы озаглавит как RAID, доступный в Windows и в Linux. В Windows, в Disk Management нужно создать Striped Volume, аналог RAID 0 (правой кнопкой мыши по нужному диску). Это когда данные пишутся параллельно на разные устройства без дублирования. Одтн блок пишется на один диск, другой на второй, причем одновременно. Чтение происходит также. Таким образом при использовании 2 дисков мы получаем двойную скорость чтения/записи.

$ yay -S ldmtool

$ sudo ldmtool scan                                                
[
  "8d0cc1a7-b10c-11e9-80d3-b42e9916909d"
]

$ sudo ldmtool show diskgroup 8d0cc1a7-b10c-11e9-80d3-b42e9916909d 
{
  "name" : "DESKTOP-VR9KKHM-Dg0",
  "guid" : "8d0cc1a7-b10c-11e9-80d3-b42e9916909d",
  "volumes" : [
    "Volume1"
  ],
  "disks" : [
    "Disk1",
    "Disk2"
  ]
}

$ sudo ldmtool create all                                          
[
  "ldm_vol_DESKTOP-VR9KKHM-Dg0_Volume1"
]

Теперь можно монтировать устройство /dev/mapper/ldm_vol_DESKTOP-VR9KKHM-Dg0_Volume1.

Но нам нужно чтобы устройство автоматически создавалось. Для этого нужно создать сервис /etc/systemd/system/ldmtool.service:

[Unit]
Description=Windows Dynamic Disk Mount
Before=local-fs-pre.target
DefaultDependencies=no
[Service]
Type=simple
User=root
ExecStart=/usr/bin/ldmtool create all
[Install]
WantedBy=local-fs-pre.target

Включим его:

$ sudo systemctl enable ldmtool.service

Редактируем /etc/fstab:

/dev/mapper/ldm_vol_DESKTOP-VR9KKHM-Dg0_Volume1 /mnt/d ntfs-3g rw,user,fmask=0111,dmask=0000 0 0

В Windows есть так же технология Storage Spaces, но ее поддержка в Linux не реализована.

Права

4 — Чтение (r)
2 — Запись (w)
1 — Выполнение (x)

Сумма этих чисел дает разные сочетания типа:
1 + 2 + 4 = 7 или 1 + 4 = 5

Права задаются тремя числами, например, 755, где первое число – права владельца, далее: группа и остальные пользователи. Владелец может делать все (1 + 2 + 4 = 7), другие пользователи – только читать и исполнять файлы (1 + 4 = 5).

Для работы с правами на файлы используется команда chroot:

В Python права можно записывать так:

$ ll
total 20K
drwxr-xr-x 3 sergey sergey 4,0K июн 20 17:22 backend
...

d         | rwx      | r-x    | r-x
тип файла | владелец | группа | остальные

Ссылки:

  • Права доступа к файлам и каталогам

Монтирование

$ sudo mount [ -t <fs> ] <device> <path> [ -o <options> ]

# Можно монтировать образы, созданные через dd
mount -t fstype -o loop,ro image.dd /mntpoint

Опции:

ro     Mount the filesystem read-only.

rw     Mount the filesystem read-write.

sync   All I/O to the filesystem should be done synchronously.  In  the
	case  of  media with a limited number of write cycles (e.g. some
	flash drives), sync may cause life-cycle shortening.

user   Allow an ordinary user to mount the filesystem.  The name of the
	mounting  user  is  written  to the mtab file (or to the private
	libmount file in /run/mount on systems without a  regular  mtab)
	so  that  this same user can unmount the filesystem again.  This
	option implies the options noexec,  nosuid,  and  nodev  (unless
	overridden   by  subsequent  options,  as  in  the  option  line
	user,exec,dev,suid).

noexec ‒ запретить выполнение файлов
noatime ‒ не обновлять время домступа к файлу
defaults = rw,suid,dev,exec,auto,nouser,async
uid ‒ 1000 для первого пользователя
gid ‒ см. далее

$ id
uid=1000(sergey) gid=985(users) groups=985(users),969(docker),998(wheel)

users  Allow any user to mount and to unmount the filesystem, even when
	some other ordinary user mounted it.  This  option  implies  the
	options  noexec,  nosuid, and nodev (unless overridden by subse‐
	quent options, as in the option line users,exec,dev,suid).

umask=value
	Set the umask (the bitmask  of  the  permissions  that  are  not
	present).  The default is the umask of the current process.  The
	value is given in octal.

dmask=value
	Set the umask applied to directories only.  The default  is  the
	umask of the current process.  The value is given in octal.

fmask=value
	Set the umask applied to regular files only.  The default is the
	umask of the current process.  The value is given in octal.

Указываются права не в виде восьмиричного числа!

    0   1   2   3   4   5   6   7
r   +   +   +   +   -   -   -   -
w   +   +   -   -   +   +   -   -
x   +   -   +   -   +   -   +   -

Например, 0755 = 0022
  • mount.

Добавляем путь в PATH

  • Bash Shell: ~.bash_profile, ~/.bashrc or ~/.profile
  • Korn Shell: ~/.kshrc or ~/.profile
  • Z Shell: ~/.zshrc or ~/.zprofile
export PATH=/path/to/bin:$PATH

bin в домашнем каталоге

mkdir ~/bin
echo 'export PATH=$HOME/bin:$PATH' >> ~/.zprofile
# or
echo 'export PATH=$HOME/bin:$PATH' >> ~/.zshrc

Теперь самописные скрипты можно кидать в ~/bin, так они будут доступны только для текущего пользователя.

~/bin/hello:

#!/usr/bin/env bash
function hello() {
  local name=${1:-World}
  printf "Hello, %s!n" $name
}
hello $@

Сделаем скрпит исполняемым:

Проверка:

# Если не перелогинивались после добавления пути в ~/.zprofile, то сначала выполняем
$ source ~/.zprofile
$ hello $USER
Hello, sergey!

Монтируем Windows разделы

Редактируем /etc/fstab:

/dev/nvme0n1p4 /mnt/c ntfs-3g rw,user,fmask=0111,dmask=0000 0 0

Шрифты

Шрифты надо кидать в /usr/share/fonts либо в ~/.fonts или в ~/.local/share/fonts.

# Обновить шрифты
$ fc-cache -f -v

# Чтобы проверить установлен ли шрифт
$ fc-list | grep "<name-of-font>"

Шарим Windows шрифты:

$ sudo ln -sf /mnt/c/Windows/Fonts /usr/share/fonts/WindowsFonts

screenshot from 2019-02-20 23-17-46

Наборы шрифтов:

  • Powrline Fonts;
  • Nerd Fonts.

Emoji

yay -S ttf-joypixels

Я не совсем понимаю как отображаются emoji. В гномовских приложения они выглядят одинаково, а в сторонних, в том же VScode рендерятся по-другому.

Спецсимволы

Для вставки специальных символов в Gnome применяется сочетание клавиш Ctrl+Shift+U, далее вводим 4-х значный код символа.

Символ Unicode
« 00ab
» 00bb
© 00a9
2122
§ 00a7
2013
20ac
20bd
2192
λ 03bb

Сетевые интерфесы

$ ifconfig -a
...
enp5s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.0.106  netmask 255.255.255.0  broadcast 192.168.0.255
...

# inet 192.168.0.106 ‒ это наш адрес в локальной сети, если запустить на локальной машине nginx, то перейдя по ссылке http://192.168.0.106 мы увидим приветствие Nginx

Расшифрорвка имен:

Two character prefixes based on the type of interface:
 *   en -- ethernet
 *   sl -- serial line IP (slip)
 *   wl -- wlan
 *   ww -- wwan

Так же можно менять свой локальный ip.

Ссылки:

(Linux ifconfig command)[https://www.computerhope.com/unix/uifconfi.htm].

Блокируем сайты с рекламой через hosts

# Сохраняем копию оригинального файла
$ cp /etc/hosts ~/Documents/hosts.bak
$ wget -qO- https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts | sudo tee --append /etc/hosts

Информация о железе

$ lspci
00:00.0 Host bridge: Intel Corporation 2nd Generation Core Processor Family DRAM Controller (rev 09)
00:01.0 PCI bridge: Intel Corporation Xeon E3-1200/2nd Generation Core Processor Family PCI Express Root Port (rev 09)
00:02.0 VGA compatible controller: Intel Corporation 2nd Generation Core Processor Family Integrated Graphics Controller (rev 09)
00:14.0 USB controller: Intel Corporation 7 Series/C210 Series Chipset Family USB xHCI Host Controller (rev 04)
00:16.0 Communication controller: Intel Corporation 7 Series/C216 Chipset Family MEI Controller #1 (rev 04)
00:1a.0 USB controller: Intel Corporation 7 Series/C216 Chipset Family USB Enhanced Host Controller #2 (rev 04)
00:1b.0 Audio device: Intel Corporation 7 Series/C216 Chipset Family High Definition Audio Controller (rev 04)
00:1c.0 PCI bridge: Intel Corporation 7 Series/C216 Chipset Family PCI Express Root Port 1 (rev c4)
00:1c.4 PCI bridge: Intel Corporation 7 Series/C210 Series Chipset Family PCI Express Root Port 5 (rev c4)
00:1c.5 PCI bridge: Intel Corporation 7 Series/C210 Series Chipset Family PCI Express Root Port 6 (rev c4)
00:1c.6 PCI bridge: Intel Corporation 7 Series/C210 Series Chipset Family PCI Express Root Port 7 (rev c4)
00:1d.0 USB controller: Intel Corporation 7 Series/C216 Chipset Family USB Enhanced Host Controller #1 (rev 04)
00:1f.0 ISA bridge: Intel Corporation H77 Express Chipset LPC Controller (rev 04)
00:1f.2 IDE interface: Intel Corporation 7 Series/C210 Series Chipset Family 4-port SATA Controller [IDE mode] (rev 04)
00:1f.3 SMBus: Intel Corporation 7 Series/C216 Chipset Family SMBus Controller (rev 04)
00:1f.5 IDE interface: Intel Corporation 7 Series/C210 Series Chipset Family 2-port SATA Controller [IDE mode] (rev 04)
03:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 09)
04:00.0 Network controller: Qualcomm Atheros AR9485 Wireless Network Adapter (rev 01)
05:00.0 IDE interface: Marvell Technology Group Ltd. 88SE9172 SATA III 6Gb/s RAID Controller (rev 11)

# Видеоадаптер(ы)
$ lspci -v | grep "VGA" -A 12

# SATA-устройства
$ lsscsi

# Список USB-устройств
$ lsusb

# Очень подробная информация о всех устройствах
$ inxi -Fx

$ hwinfo --short
cpu:
                       Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz, 3500 MHz
                       Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz, 3480 MHz
                       Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz, 3500 MHz
                       Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz, 3491 MHz
                       Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz, 3550 MHz
                       Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz, 3484 MHz
                       Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz, 3492 MHz
                       Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz, 3496 MHz
keyboard:
  /dev/input/event2    Logitech Keyboard K120
mouse:
  /dev/input/mice      Logitech M-U0004 810-001317 [B110 Optical USB Mouse]
monitor:
                       SAMSUNG SMS24A650
                       SAMSUNG SMB2340
graphics card:
                       Intel 2nd Generation Core Processor Family Integrated Graphics Controller
sound:
                       Intel 7 Series/C216 Chipset Family High Definition Audio Controller
storage:
                       Intel 7 Series/C210 Series Chipset Family 4-port SATA Controller [IDE mode]
                       Intel 7 Series/C210 Series Chipset Family 2-port SATA Controller [IDE mode]
                       Marvell 88SE9172 SATA III 6Gb/s RAID Controller
network:
  enp3s0               Realtek RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller
  wlp4s0               Qualcomm Atheros AR9485 Wireless Network Adapter
network interface:
  docker0              Ethernet network interface
  enp3s0               Ethernet network interface
  lo                   Loopback network interface
  wlp4s0               Ethernet network interface
  br-1d7c88a3dc61      Ethernet network interface
disk:
  /dev/sdb             WDC WD5000AZLX-0
  /dev/sda             INTEL SSDSC2CW24
partition:
  /dev/sdb1            Partition
  /dev/sda1            Partition
  /dev/sda2            Partition
  /dev/sda3            Partition
usb controller:
                       Intel 7 Series/C216 Chipset Family USB Enhanced Host Controller #2
                       Intel 7 Series/C216 Chipset Family USB Enhanced Host Controller #1
                       Intel 7 Series/C210 Series Chipset Family USB xHCI Host Controller
bios:
                       BIOS
bridge:
                       Intel 7 Series/C216 Chipset Family PCI Express Root Port 1
                       Intel H77 Express Chipset LPC Controller
                       Intel Xeon E3-1200/2nd Generation Core Processor Family PCI Express Root Port
                       Intel 7 Series/C210 Series Chipset Family PCI Express Root Port 6
                       Intel 2nd Generation Core Processor Family DRAM Controller
                       Intel 7 Series/C210 Series Chipset Family PCI Express Root Port 7
                       Intel 7 Series/C210 Series Chipset Family PCI Express Root Port 5
hub:
                       Intel Integrated Rate Matching Hub
                       Linux Foundation 2.0 root hub
                       Linux Foundation 3.0 root hub
                       Linux Foundation 2.0 root hub
                       Intel Integrated Rate Matching Hub
                       Linux Foundation 2.0 root hub
memory:
                       Main Memory
unknown:
                       FPU
                       DMA controller
                       PIC
                       Keyboard controller
  /dev/lp0             Parallel controller
                       Intel 7 Series/C216 Chipset Family MEI Controller #1
                       Intel 7 Series/C216 Chipset Family SMBus Controller
                       Serial controller
  /dev/input/event3    Logitech Keyboard K120

# Список блочных устройств
$ lsblk

# Покажет разделы и занимаемое ими место
$ df -h

# Fdisk is a utility to modify partitions on hard drives, and can be used to list out the partition information as well.

$ sudo fdisk -l

Disk /dev/sda: 500.1 GB, 500107862016 bytes
255 heads, 63 sectors/track, 60801 cylinders, total 976773168 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
Disk identifier: 0x30093008

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *          63   146801969    73400953+   7  HPFS/NTFS/exFAT
/dev/sda2       146802031   976771071   414984520+   f  W95 Ext'd (LBA)
/dev/sda5       146802033   351614654   102406311    7  HPFS/NTFS/exFAT
/dev/sda6       351614718   556427339   102406311   83  Linux
/dev/sda7       556429312   560427007     1998848   82  Linux swap / Solaris
/dev/sda8       560429056   976771071   208171008   83  Linux

# The mount is used to mount/unmount and view mounted file systems.

$ mount | column -t
/dev/sda6    on  /                                            type  ext4             (rw,errors=remount-ro)
proc         on  /proc                                        type  proc             (rw,noexec,nosuid,nodev)
sysfs        on  /sys                                         type  sysfs            (rw,noexec,nosuid,nodev)
none         on  /sys/fs/cgroup                               type  tmpfs            (rw)
none         on  /sys/fs/fuse/connections                     type  fusectl          (rw)
none         on  /sys/kernel/debug                            type  debugfs          (rw)
none         on  /sys/kernel/security                         type  securityfs       (rw)
udev         on  /dev                                         type  devtmpfs         (rw,mode=0755)
devpts       on  /dev/pts                                     type  devpts           (rw,noexec,nosuid,gid=5,mode=0620)
tmpfs        on  /run                                         type  tmpfs            (rw,noexec,nosuid,size=10%,mode=0755)
none         on  /run/lock                                    type  tmpfs            (rw,noexec,nosuid,nodev,size=5242880)
none         on  /run/shm                                     type  tmpfs            (rw,nosuid,nodev)
none         on  /run/user                                    type  tmpfs            (rw,noexec,nosuid,nodev,size=104857600,mode=0755)
none         on  /sys/fs/pstore                               type  pstore           (rw)
/dev/sda8    on  /media/13f35f59-f023-4d98-b06f-9dfaebefd6c1  type  ext4             (rw,nosuid,nodev,errors=remount-ro)
/dev/sda5    on  /media/4668484A68483B47                      type  fuseblk          (rw,nosuid,nodev,allow_other,blksize=4096)
binfmt_misc  on  /proc/sys/fs/binfmt_misc                     type  binfmt_misc      (rw,noexec,nosuid,nodev)
systemd      on  /sys/fs/cgroup/systemd                       type  cgroup           (rw,noexec,nosuid,nodev,none,name=systemd)
gvfsd-fuse   on  /run/user/1000/gvfs                          type  fuse.gvfsd-fuse  (rw,nosuid,nodev,user=enlightened)

# Again, use grep to filter out only those file systems that you want to see

$ mount | column -t | grep ext

# The dmidecode command is different from all other commands. It extracts hardware information by reading data from the SMBOIS data structures (also called DMI tables).

# display information about the processor/cpu
$ sudo dmidecode -t processor

# memory/ram information
$ sudo dmidecode -t memory

# bios details
$ sudo dmidecode -t bios

# cpu information
$ cat /proc/cpuinfo

# memory information
$ cat /proc/meminfo

$ cat /proc/version
Linux version 3.11.0-12-generic (buildd@allspice) (gcc version 4.8.1 (Ubuntu/Linaro 4.8.1-10ubuntu7) ) #19-Ubuntu SMP Wed Oct 9 16:20:46 UTC 2013

# SCSI/Sata devices

$ cat /proc/scsi/scsi
Attached devices:
Host: scsi3 Channel: 00 Id: 00 Lun: 00
  Vendor: ATA      Model: ST3500418AS      Rev: CC38
  Type:   Direct-Access                    ANSI  SCSI revision: 05
Host: scsi4 Channel: 00 Id: 00 Lun: 00
  Vendor: SONY     Model: DVD RW DRU-190A  Rev: 1.63
  Type:   CD-ROM                           ANSI  SCSI revision: 05
Partitions

$ cat /proc/partitions
major minor  #blocks  name

   8        0  488386584 sda
   8        1   73400953 sda1
   8        2          1 sda2
   8        5  102406311 sda5
   8        6  102406311 sda6
   8        7    1998848 sda7
   8        8  208171008 sda8
  11        0    1048575 sr0

# The hdparm command gets information about sata devices like hard disks.

$ sudo hdparm -i /dev/sda

/dev/sda:

 Model=ST3500418AS, FwRev=CC38, SerialNo=9VMJXV1N
 Config={ HardSect NotMFM HdSw>15uSec Fixed DTR>10Mbs RotSpdTol>.5% }
 RawCHS=16383/16/63, TrkSize=0, SectSize=0, ECCbytes=4
 BuffType=unknown, BuffSize=16384kB, MaxMultSect=16, MultSect=16
 CurCHS=16383/16/63, CurSects=16514064, LBA=yes, LBAsects=976773168
 IORDY=on/off, tPIO={min:120,w/IORDY:120}, tDMA={min:120,rec:120}
 PIO modes:  pio0 pio1 pio2 pio3 pio4
 DMA modes:  mdma0 mdma1 mdma2
 UDMA modes: udma0 udma1 udma2 udma3 udma4 udma5 *udma6
 AdvancedPM=no WriteCache=enabled
 Drive conforms to: unknown:  ATA/ATAPI-4,5,6,7

 * signifies the current active mode

Редактирование DConf

DConf хранит профили терминала в ~/.config/dconf/user, в формате GVDB пруф.

image

# Делаем дамп
$ dconf dump / > /tmp/dconf
# Редактируем и загружаем
$ dconf load / < /tmp/dconf

ZSH

Установка ZSH

Меняем shell на /bin/zsh:

Чтобы изменения вступили в силу нужно залогиниться по-новой.


## [Oh My Zsh](https://github.com/robbyrussell/oh-my-zsh)

Установка:

sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"

Пакет из репозитория ставится вне домашнего каталога, а потому требует root права при установке плагинов, что не удобно.

Так же для некоторых тем Oh My Zsh нужны шрифты наподобие Powerline:

Ставим must-have плагины:

git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions
git clone https://github.com/zsh-users/zsh-completions ${ZSH_CUSTOM:=~/.oh-my-zsh/custom}/plugins/zsh-completions
git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting

Изменяем .zshrc:

ZSH_THEME="agnoster"
...
plugins=(
  command-not-found
  extract
  git
  zsh-autosuggestions
  zsh-completions
  zsh-syntax-highlighting
)

autoload -Uz compinit && compinit

source $ZSH/oh-my-zsh.sh

Для темы Agnoster настройках терминала выбираем шрифт Source Code Pro Regular, чтобы отображались стрелочки.

  • Встроенные темы;
  • Сторонние темы;
  • Так же можно поискать на Github’е.

ZGen

Позволяет избавиться от мусора в ~/.zshrc.

Пример файла ~/.zshrc:

# load zgen
source /usr/share/zsh/share/zgen.zsh

# if the init script doesn't exist
if ! zgen saved; then

  # specify plugins here
  zgen oh-my-zsh
  zgen oh-my-zsh plugins/git
  zgen oh-my-zsh plugins/sudo
  zgen oh-my-zsh plugins/command-not-found
  zgen oh-my-zsh plugins/extract 
  zgen load zsh-users/zsh-autosuggestions
  zgen load zsh-users/zsh-completions
  zgen load zsh-users/zsh-syntax-highlighting
  zgen load caiogondim/bullet-train-oh-my-zsh-theme bullet-train

  # generate the init script from plugins above
  zgen save
fi

После изменения .zshrc делаем zgen reset, а потом exec "$SHELL"?

См. справку:

Темы Oh My Zsh!

Bullet Train for oh-my-zsh

$ wget -P $ZSH_CUSTOM/themes https://raw.githubusercontent.com/caiogondim/bullet-train-oh-my-zsh-theme/master/bullet-train.zsh-theme

Jovial

# Сначала сохраняем копию zhsrc, потому как jovial изменить оригинальеный файл
$ cp ~/.zshrc ~/.zshrc.bak
$ curl -sSL git.io/jovial | sudo bash -s $USER

У меня эта тема упорно устанавливается в /root/.oh-my-zsh.

Powerlevel10k

Это красивая тема для ZSH.

git clone https://github.com/romkatv/powerlevel10k.git $ZSH_CUSTOM/themes/powerlevel10k

~/.zshrc:

ZSH_THEME=powerlevel10k/powerlevel10k

Изменим prompt:

cd && curl -fsSLO https://raw.githubusercontent.com/romkatv/dotfiles-public/master/.purepower
echo 'source ~/.purepower' >>! ~/.zshrc

image

Подробнее про ZSH

  • Приемы при работе с ZSH.

Разноцветный cat

  • ccat;
  • lolcat.

Цветовые схемы для терминала

# Интерактивная установка
# Падает с ошибкой, если нет профиля по-умолчаниюю для терминала
# Для всех созданных профилей будет использовавться шрифт профиля по-умолчанию
bash -c  "$(wget -qO- https://git.io/vQgMr)"
# Удаление всех профилей
dconf reset -f /org/gnome/terminal/legacy/profiles:/

Ссылки:

  • Обзор тем.

Бекап системы

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

mkdir /mnt/{backup,root}
mount /path/to/backup /mnt/backup
mount /path/to/root /mnt/root

# Делаем бекап
cd /mnt/root
tar -cvpzf /mnt/backup/root.tar.gz .

# Извлекаем бекапа
tar -xzpvf /mnt/backup/root.tar.gz -C /mnt/root

Ссылки:

  • Делаем бекап системы с помощью tar.

asdf-vm

Установка asdf через Git:

git clone https://github.com/asdf-vm/asdf.git ~/.asdf
cd ~/.asdf
git checkout "$(git describe --abbrev=0 --tags)"

echo -e 'n. $HOME/.asdf/asdf.sh' >> ~/.zshrc
echo -e 'n. $HOME/.asdf/completions/asdf.bash' >> ~/.zshrc

Установка asdf через AUR:

В ~/.zshrc (после compinit) добавляем строки:

. /opt/asdf-vm/asdf.sh
. /opt/asdf-vm/completions/asdf.bash

В ~/.zprofile:

export PATH=/opt/asdf-vm/bin:$PATH

Эту строку можно и в ~/.zshrc.

Удаление:

rm -rf ~/.asdf/ ~/.tool-versions

Примеры:

$ asdf plugin-add python
$ asdf install python 3.7.3
$ asdf install python 2.7.15
$ asdf list python
  2.7.15
  3.7.3
$ asdf uninstall python 2.7.15
$ asdf global python 3.7.3
# Сделать системную версию Python глобальной
$ asdf global python system
$ which python
/home/sergey/.asdf/shims/python

$ asdf plugin-add nodejs
# see: <https://github.com/asdf-vm/asdf-nodejs#install>
$ bash ~/.asdf/plugins/nodejs/bin/import-release-team-keyring
$ asdf install nodejs 10.16.0
$ asdf global nodejs 10.16.0
$ which node
/home/sergey/.asdf/shims/node
$ which npm
/home/sergey/.asdf/shims/npm
$ asdf list
golang
  1.12
nodejs
  10.16.0
postgres
  11.4
python
  2.7.15
  3.7.3
sqlite
  3.29.0

Все доступные плагины. При установке, использовании плагинов могут возникать проблемы. Например, плагин для Python работает поверх pyenv и при возникновении проблем, следует изучить страницу «Common build problems».

If you use pip to install a module like ipython that has a binaries. You will need to run asdf reshim python for the binary to be in your path.

После установки через pip пакетов, которые добавляют команды, чтобы те были доступны, нужно всегда выполнять asdf reshim python.

Ссылки:

  • Документация.

NVM

⚠️ Использование asdf-vm предпочительнее.

Устанавливаем последнюю версию Node.js:

Настройка Docker

$ yay -S docker
$ sudo systemctl start docker
$ sudo systemctl enable docker
# sudo groupadd docker
# groupadd: group 'docker' already exists
sudo usermod -aG docker $USER

Нужно выйти и войти в систему, а потом проверить:

Ссылка.

Настройка Visual Code

{
  "editor.fontSize": 16,
  "editor.rulers": [
    72,
    80,
    100,
    120
  ],
  "editor.tabSize": 2,
  "editor.wordWrap": "bounded",
  "editor.wordWrapColumn": 120,
  "files.insertFinalNewline": true,
  "files.trimFinalNewlines": true,
  "files.trimTrailingWhitespace": true,
  "terminal.integrated.fontFamily": "Source Code Pro"
}

LVM

Список логических разделов LVM:

$ sudo lvscan
  ACTIVE            '/dev/linux/root' [40.00 GiB] inherit
  ACTIVE            '/dev/linux/home' [20.00 GiB] inherit

Изменение размера логического раздела:

# Ключ -r выполняет resizefs
$ lvresize -r -L +10G /dev/linux/home

# Аналогично двум командам:

# Увеличиваем размер логического раздела
$ sudo lvresize -L +10GB /dev/mapper/linux-home

# После lvresize нужно обязательно изменить размер файловой системы
$ sudo resize2fs /dev/mapper/linux-home

# Делает то же самое, что и две команды выше
$ sudo lvresize -r -L +10GB /dev/mapper/linux-root

Переименование логического раздела:

$ sudo lvrename <oldname> <newname>

После нужно отредактировать /etc/fstab, изменив пути до разделов, а затем выполнить:

$ sudo grub-mkconfig -o /boot/grub/grub.cfg

Btrfs

Про снапшоты. В Btrfs есть механизм, аналогичный git, который позволяет фиксировать изменения снимками. Снапшоты хранят в себе только изменения между снимками, поэтому занимают мало места и по этой же причине не могут быть созданы вне текущей файловой системы. Они содержат только диффы. Как только мы создали снапшот, состояние системы зафиксировалось. Например у нас есть три файла: foo, bar, baz. Мы сделали снапшот, а потом удалили foo и baz, но пока существует снапшот эти файлы продолжат занимать место + если мы изменим bar, то и его первоначальная копия продолжит свое существование. Так что чтобы освободить место придется периодически удалять ненужные снапшоты.

Обнаружил баг: из-за своп-файла не делались снапшоты корня.

# Создать subvolume
$ sudo btrfs sub create /path/to/@name

# Создание снапшота
# Снапшоты являются разновидностью полдазделов, потому с ними можно выполнять те же операции
$ sudo mkdir /.snapshots
$ sudo chmod 750 /.snapshots

# Этой командой не получится создать снапшот на другой Btrfs (на флешке)
$ sudo btrfs sub snap -r /home /.snapshots/@home_`date +%F-%s`
Create a readonly snapshot of '/home' in '/.snapshots/@home_2019-07-15-1563181292'

$ sudo btrfs sub li -a /
ID 257 gen 1457 top level 5 path <FS_TREE>/@
ID 258 gen 1458 top level 5 path <FS_TREE>/@home
ID 281 gen 1458 top level 5 path <FS_TREE>/@var
ID 283 gen 1458 top level 257 path <FS_TREE>/@/.snapshots/@home_2019-07-15-1563181292

# Удаление снапшота аналогично удалению подраздела
$ sudo btrfs sub del /.snapshots/@home_2019-07-15-1563181292
Delete subvolume (no-commit): '/.snapshots/@home_2019-07-15-1563181292'

# Смонтировать subvolume/снапшот по указанному пути
$ sudo btrfs sub set-default <ID> /

# Восстановление данных

# С сохранением снапшота
$ cp -aR --reflink /.snapshots/@home_YYYY-MM-DD-ssssssssss /@home

# С удалением снапшота
# Таким же способом можно переименовывать подразделы/снапшоты
$ mv /.snapshots/@home_YYYY-MM-DD-ssssssssss /@home

$ btrfs filesystem df /
Data, single: total=15.01GiB, used=12.42GiB
System, single: total=4.00MiB, used=16.00KiB
Metadata, single: total=1.01GiB, used=772.20MiB
GlobalReserve, single: total=44.47MiB, used=0.00B

# Как сделать бекап и восстановить его в другой ФС
$ btrfs send /source/subvolume >/another/filesystem/subvolume-image   # just a file
# (or you can gzip it and/or send with nc on the fly, whatever)
# then later
$ </another/filesystem/subvolume-image btrfs receive /some/btrfs/directory

# Можно так же добавлять новые разделы и устройства в уже существующую ФС
# Можно так же сделатиь ограничения на размер подраздела, добавив его в группу и включив для него квоту
$ man btrfs
бтрфс ничего не жмет.
наилучший вариант сделать ридонли снапшот системы, потом из снапшота сделать образ через send и уж его можно жать и в хвост и в гриву
к примеру

sudo btrfs filesystem sync /
sudo btrfs subvolume snapshot -r / /mnt/backup/root_base
sudo btrfs send /mnt/b11/root_base | gzip > root_`date '+%F'`.gz

но почему бы не воспользоваться обыденным tar ??
так-то формат упаковки btrfs-stream (формат выхода btrfs send) не фундаментально отличается от формата tar. выполнить на сервере

sudo tar -czpf %backup%/srv4full-`date "+%F"`.tgz -X /etc/backupfull_exclude /

в файл /etc/backupfull_exclude пишешь список того что не нужно упаковывать в архив с системой (кроме классических /dev /proc /run /sys и прочих еще докинуть саму директорию куда архивишься  и плюс рабочие директории сервисов, к примеру база данных такую архивацию не всегда переживет)
а далее восстановление из tar архива

если свободного места на сервере будет меньше трети всего объема то такой бекап может не прокатить, либо жать сильнее к примеру через lzma (жрет памяти и проц очень хорошо) либо писать напрямую по интернету к себе (если будет разрыв то передача обломится)

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

Flat:

toplevel         (volume root directory, not to be mounted by default)
  +-- root       (subvolume root directory, to be mounted at /)
  +-- home       (subvolume root directory, to be mounted at /home)
  +-- var        (directory)
  |   -- www    (subvolume root directory, to be mounted at /var/www)
  -- postgres   (subvolume root directory, to be mounted at /var/lib/postgresql)

Nested:

toplevel                  (volume root directory, to be mounted at /)
+-- home                  (subvolume root directory)
+-- var                   (subvolume root directory)
    +-- www               (subvolume root directory)
    +-- lib               (directory)
         -- postgresql   (subvolume root directory)

Snapper

Snapper ‒ это утилита для управления снапшотами для LVM и Btrfs.

# Установка
$ yay -S snapper

# Глобальные настройки
$ sudo nano /etc/conf.d/snapper

# Из этого шаблона генерируются другие конфиги
# Тут мы увеличим время после которого снапшоты будут удаляться до 24 часов
$ sudo sed -ri 's/MIN_AGE="[0-9]+"/MIN_AGE="86400"/g' /etc/snapper/config-templates/default

# Создаем конфиги для каждого подраздела отдельно
$ sudo snapper -c root create-config /
$ sudo snapper -c home create-config /home
$ sudo snapper -c var create-config /var

# Сгенерированные шаблоны находятся в /etc/snapper/configs

# Список конфигов
$ sudo snapper list-configs
Config | Subvolume
-------+----------
home   | /home
root   | /
var    | /var

# Созданные конфиги меют такой адрес: /etc/snapper/configs/<config>

# Список снапшотов для конфига
$ snapper -c CONFIG list

# Удаление конфига
$ sudo snapper -c CONFIG delete-config

# Создать новый снапшот
$ snapper -c CONFIG snapshot

# Удалить снапшот
$ snapper -c CONFIG delete snapshot_number

# Удалить диапазон снапшотов
$ snapper -c CONFIG delete snapshot_X-snapshot_Y

<<<<<<< HEAD
# Включаем автоматическое создания снапшотов
# Запускаем бекап через 5 минут после загрузки и далее каждые 24 часа
=======
# Добавляем .snapshots в исключения для mlocate
$ sudo nano /etc/updatedb.conf
...
PRUNENAMES = ".git .hg .svn .snapshots"
...

# Делаем снимки через 5 минут после загрузки и далее каждые 24 часов
>>>>>>> c67ee04f7511ffe5c7ed83f2c751da05ac42de29
$ sudo nano $(locate snapper-timeline.timer)
...
[Timer]
OnBootSec=5min
OnUnitActiveSec=24h
...

# Включаем автоматическое создания снапшотов
$ sudo systemctl enable snapper-timeline.timer && sudo systemctl start snapper-timeline.timer

# Можно так же периодичность очистки снапшотов изменить
$ sudo nano $(locate snapper-cleanup.timer)

# Автоматически  удаляет снапшоты при превышении квот
$ sudo systemctl enable snapper-cleanup.timer && sudo systemctl start snapper-cleanup.timer

# Просмотр логов
$ tail -f /var/log/snapper.log

Описание настроек:

### SNAPPER-CONFIGS(5)# Filesystem Snapshot Management
### Boolean values must be "yes" or "no".

SUBVOLUME="/"
        # Path of the subvolume or mount point.
        # There is no default value. The value must always be specified.

FSTYPE=btrfs
        # Filesystem type for the subvolume.
        # Default value is "btrfs" but it's recommended to always specify the
        # filesystem type.

ALLOW_USERS=""
        # List of users allowed to operate with the config. The user-names
        # must be separated by spaces. Spaces in usernames can be escaped with
        # a "".
        # Also see the PERMISSONS section in snapper(8).
        # Default value is "" but "root" is always implicitly included.

ALLOW_GROUPS="snapper"
        # List of groups allowed to operate with the config. The group-names
        # must be separated by spaces. Spaces in group-names can be escaped
        # with a "".
        # Also see the PERMISSONS section in snapper(8).
        # Default value is "".

SYNC_ACL=yes
        # Defines whether snapper will sync the users and groups from
        # ALLOW_USERS and ALLOW_GROUPS to the ACL of the .snapshots directory.
        # Also see the PERMISSONS section in snapper(8).
        # Default value is "no".
        # New in version 0.2.0.

BACKGROUND_COMPARISON=yes
        # Defines whether pre and post snapshots should be compared in the
        # background after creation.
        # Default value is "yes".

### CLEANUP ALGORITHMS
######################

### NUMBER
NUMBER_CLEANUP=no
        # Defines whether the number cleanup algorithm should be run for the
        # config.
        # Default value is "no".

NUMBER_MIN_AGE=1800
        # Minimal age for snapshots to be deleted by the number cleanup
        # algorithm.
        # Default value is "1800".

NUMBER_LIMIT=50
        # Defines how many snapshots the number cleanup algorithm should
        # keep. The youngest snapshots will be kept.
        # Default value is "50".

NUMBER_LIMIT_IMPORTANT=10
        # Defines how many important snapshots the number cleanup algorithm
        # should keep. Important snapshots have important=yes in the userdata.
        # The youngest important snapshots will be kept.
        # The number of normal and important snapshots are counted
        # independently.
        # Default value is "10".
        # New in version 0.1.8.

### TIMELINE
TIMELINE_CREATE=yes
        # Defines whether hourly snapshots should be created.
        # Together with the timeline cleanup algorithm this will create a
        # collection of snapshots with more snapshots is the near past and less
        # snapshots in the far past.
        # Default value is "no".

TIMELINE_CLEANUP=yes
        # Defines whether the timeline cleanup algorithm should be run for
        # the config.
        # Default value is "no".

TIMELINE_MIN_AGE=14400
        # Minimal age for snapshots to be deleted by the timeline cleanup
        # algorithm.
        # Default value is "1800".

TIMELINE_LIMIT_HOURLY=23
        # Defines how many hourly snapshots the timeline cleanup algorithm
        # should keep. An hourly snapshot is the first snapshot in an hour. The
        # youngest hourly snapshots will be kept.
        # Default value is "10".

TIMELINE_LIMIT_DAILY=14
        # Defines how many daily snapshots the timeline cleanup algorithm
        # should keep. A daily snapshot is the first snapshot in a day. The
        # youngest daily snapshots will be kept.
        # Default value is "10".

TIMELINE_LIMIT_MONTHLY=6
        # Defines how many monthly snapshots the timeline cleanup algorithm
        # should keep. A monthly snapshot is the first snapshot in a month. The
        # youngest monthly snapshots will be kept.
        # Default value is "10".

TIMELINE_LIMIT_YEARLY=1
        # Defines how many yearly snapshots the timeline cleanup algorithm
        # should keep. A yearly snapshot is the first snapshot in a year. The
        # youngest yearly snapshots will be kept.
        # Default value is "10".

### EMTPY PRE POST
EMPTY_PRE_POST_CLEANUP=yes
        # Defines whether the empty-pre-post cleanup algorithm should be run
        # for the config.
        # Default value is "no".

EMPTY_PRE_POST_MIN_AGE=1800
        # Minimal age for snapshots to be deleted by the empty-pre-post
        # cleanup algorithm.
        # Default value is "1800".

GUI:

# Не запускается
$ yay -S snapper-gui-git

Ссылки:

  • Snapper;
  • Systemd/Timers.

Timeshift

Программа для управления бекапами. Работает с Btrfs и в rsync-режиме (полный дамп).

Логи

# Как посмотреть логи?
$ less /var/log/messages
$ more -f /var/log/messages
$ cat /var/log/messages
$ tail -f /var/log/messages
$ grep -i error /var/log/messages

# Сообщения ядра Linux
$ dmesg | less
Файл Описание
/var/log/messages General message and system related stuff
/var/log/auth.log Authenication logs
/var/log/kern.log Kernel logs
/var/log/cron.log Crond logs (cron job)
/var/log/maillog Mail server logs
/var/log/qmail/ Qmail log directory (more files inside this directory)
/var/log/httpd/ Apache access and error logs directory
/var/log/lighttpd/ Lighttpd access and error logs directory
/var/log/boot.log System boot log
/var/log/mysqld.log MySQL database server log file
/var/log/secure or /var/log/auth.log Authentication log
/var/log/utmp or /var/log/wtmp Login records file
/var/log/yum.log Yum command log file.

Установка и настройка Postgres

[sergey@sergey-pc ~]$ sudo pacman -S postgresql
[sergey@sergey-pc ~]$ sudo chown postgres /var/lib/postgres/data
[sergey@sergey-pc ~]$ sudo -i -u postgres
[postgres@sergey-pc ~]$ initdb  -D '/var/lib/postgres/data'
[postgres@sergey-pc ~]$ logout
[sergey@sergey-pc ~]$ sudo systemctl start postgresql
[sergey@sergey-pc ~]$ sudo systemctl enable postgresql
[sergey@sergey-pc ~]$ sudo -u postgres -i initdb --locale $LANG -E UTF8 -D /var/lib/postgres/data
[sergey@sergey-pc ~]$
[postgres@sergey-pc ~]$ createuser --interactive -P
Enter name of role to add: sergey
Enter password for new role:
Enter it again:
Shall the new role be a superuser? (y/n)
Please answer "y" or "n".
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) y
Shall the new role be allowed to create more new roles? (y/n) y
[postgres@sergey-pc ~]$ createdb -O sergey sergey # создаем пользователя и БД с именами совпадающими с пользователем системы, чтобы psql запускать без параметров
[postgres@sergey-pc ~]$ logout
[sergey@sergey-pc ~]$ psql
psql (11.1)
Type "help" for help.

sergey=>

# Дамп базы схемы БД
$ pg_dump -d db -f /tmp/dump.sql
# Загрузка дампа
$ psql db < /tmp/dump.sql

Мониторинг процессов

# Замена стандартному top
$ yay -S htop
$ htop

systemd

# Все сервисы

# Покажут только включенные
$ systemctl
$ systemctl list-units --type service

# + выключенные
$ systemctl list-unit-files --type service

$ sudo systemctl enable docker

$ sudo systemctl disable docker

$ sudo systemctl restart nginx.service

$ sudo systemctl start application.service

$ sudo systemctl start application.service

$ systemctl status nginx.service

$ sudo systemctl is-enabled service

Создание своего сервиса:

/etc/systemd/system/rot13.service:

[Unit]
Description=ROT13 demo service
After=network.target
StartLimitIntervalSec=0
[Service]
Type=simple
Restart=always
RestartSec=1
User=centos
ExecStart=/usr/bin/env php /path/to/server.php

[Install]
WantedBy=multi-user.target

Ссылки:

  • Timers.

Git

# Установка
$ yay -S git

# Глобальные настройки
$ git config --global user.name <yourname>
$ git config --global user.email <email>

# Цветной вывод
$ git config --global color.ui true

# Сменить ветку
$ git checkout <branchname>

# Создать ветку и переключится на нее
$ git checkout -b <branchname>

# Объединить текущую ветку с branchname
$ git merge <branchname>

# Добавить изменения (все файлы в каталоге и вложеннхы)
$ git add .

# Закоммитить изменения (сделать описание)
$ git commit -m "Тест"

# Если не были добавлены новые файлы, а лишь производились изменения в уже добавленных, то можно использовать только одну команду
$ git commit -am "Тест"

# Обновить репозиторий на сервере
$ git push

# Выгрузить изменения с сервера (тоже самое, что git fetch + git merge)
$ git pull

# Копировать репозиторий
$ git clone https://github.com/someuser/repo.git [<assigneddirectory>]

# Посмотреть историю
$ git log --graph --oneline --decorate --all

# Посмотреть отличия по сравнения с предыдущей версией
$ git diff 871d36b [<filename>]

# Сохранить изменения
$ git stash [save "my stash message here"]

# Удалить stach и применить его
$ git stash pop [stash@{1}]

# Список stash
$ git stash list

# Посмотреть что там лежит
$ git stash show stash@{0}

$ git stash apply
$ git stash drop stash@{2}
$ git stash clear

# List all the tags:

$ git tag

# Search tags for a particular pattern:

$ git tag -l <tag-pattern>

# Show a tag data:

$ git show <tag-name>

# Create a Lightweight Tag:

$ git tag <tag-name>

# Create an Annotated Tag:

$ git tag -a <tag-name> -m <tag-message>

# Create a tag for a specific commit:

$ git tag -a <tag-name> <commit-checksome>

# Push a specific tag to remote:

$ git push origin <tag-name>

# Push all the tags to remote:

$ git push origin --tags

# Checkout a specific to local:

$ git checkout -b <branch-name> <tag-name>

Работаем с github через ssh

Генерация нового ключа:

$ ssh-keygen -t rsa -b 4096 -C "<email>"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/sergey/.ssh/id_rsa): /home/sergey/.ssh/github_rsa
Created directory '/home/sergey/.ssh'.
...

В настройках нужно добавить сгенерированный ключ, скопировав содержимое pub-файла (для примера — github_rsa.pub), который лежит в ~/.ssh.

Если уже есть проекты, которые были ранее склонированы по https, то нужно изменить .git/config проекта. :

...
[remote "origin"]
url = git@github.com:<username>/<project>.git
...

Правильный адрес проекта можно посмотреть на странице репозитория:

image

Для проекта можно указать локальные email и имя:

git config user.email <email>
git config user.name <name>

Tor Service

Включаем Tor:

sudo systemctl start tor
sudo systemctl enable tor

Проверка:

$ torify curl http://httpbin.org/ip
{
  "origin": "173.244.209.5, 173.244.209.5"
}

Менеджер паролей pass

$ yay -S pass
# Далее нужно сгенерировать PGP ключ. Сгенерированный ключ можно удалить через seahorse
$ gpg2 --gen-key
gpg (GnuPG) 2.2.16; Copyright (C) 2019 Free Software Foundation, Inc.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Note: Use "gpg --full-generate-key" for a full featured key generation dialog.

GnuPG needs to construct a user ID to identify your key.

Real name: Sergey M
Email address: tz4678@gmail.com
You selected this USER-ID:
    "Sergey M <tz4678@gmail.com>"

Change (N)ame, (E)mail, or (O)kay/(Q)uit? O
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
gpg: key 82AD537DDC8DD344 marked as ultimately trusted
gpg: revocation certificate stored as '/home/sergey/.gnupg/openpgp-revocs.d/<gpg_id>.rev'
public and secret key created and signed.

pub   rsa2048 2019-07-13 [SC] [expires: 2021-07-12]
      <gpg_id>
uid                      Sergey M <tz4678@gmail.com>
sub   rsa2048 2019-07-13 [E] [expires: 2021-07-12]

# Теперь инициализируем хранилище
$ pass init gpg_id

# Можем сгенерировать пароль (будет автоматически сохранен)
$ pass generate example.com 15
The generated password for example.com is:
'.kXKEs<lx4dcKM

# Посмотреть пароль (потребует passphrase)
$ pass example.com
'.kXKEs<lx4dcKM

# Копировать пароль в буфер обмена
$ pass -c example.com
Copied example.com to clipboard. Will clear in 45 seconds.

# Удалить пароль
$ pass rm example.com
Are you sure you would like to delete example.com? [y/N] y
removed '/home/sergey/.password-store/example.com.gpg'

Базу паролей можно разместить на Google Диск.

Ссылки:

  • Pass — утилита для хранения паролей в Linux;
  • Приложение для Android;
  • Устаревшее расширение для Chrome.

Частые проблемы

Система не грузится дальше rootfs

Нужно пофиксить разделы:

Пример: у нас на диске есть два ntfs раздела раздела, а за ними идет раздел Linux, мы в Windows удаляем ntfs-2, а размер ntfs-1 увеличиваем на все освободившееся пространство, в итоге Windows выходит за свои границы и портит раздел Linux. Вывод: нужно между разделами Windows и Linux оставлять пару мегабайт свободного места.

Grub Rescue

Чаще всего эта ошибка происходит после переименования логических разделов LVM, подразделов Btrfs, переноса системы на новый раздел (когда не совпадают GUID’ы).

error: ... not found.
Entering rescue mode...

# Для начала нужно посмотреть все устройства и разделы
grub rescue> ls
(hd0) (hd1) (hd1,gpt1) (hd2) (hd2,gpt5) (hd2,gpt4) (hd2,gpt3) (hd2,gpt2) (hd2,gpt1) (hd3,gpt2) (hd3,gpt1) (hd4) (hd5)

# Мы помним, что наша система находится на 5 разделе, так что тут гадать не нужно
grub rescue> set prefix=(hd2,gpt5)/@/boot/grub
# «@» ‒ это имя подраздела Btrfs. Для обычного Ext4 раздела, команда будет выглядеть так:
#
#   set prefix=(hd2,gpt5)/boot/grub
#
# А для LVM:
#
#  set prefix=(lvm/arch-root)/boot/grub
grub rescue> set root=(hd2,gpt5)

# Проверим
grub rescue> ls /
@/ @home

# Да, это наш корневой раздел Linux
# Теперь можно загрузиться в систему
grub rescue> insmod normal
grub rescue> normal

После загрузки системы нужно переустановить grub:

$ sudo grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id="Arch Linux"
$ sudo grub-mkconfig -o /boot/grub/grub.cfg

Случайно нажали Ctrl + Alt + F* и экран стал темным

Это переключение между виртуальными терминалами. с 1-6 текстовые, остальные ‒ графические. В gdm Ctrl+Alt+F1 ‒ логин в систему, Ctrl+Alt+F2 ‒ рабочий стол. В lightdm переключиться на рабочий стол можно нажатием Ctrl+Alt+F7.

Что делать, если каталоги открываются в VSCode?

Существует файл /usr/share/applications/mimeinfo.cache. В нем хранятся ассоциации между mime-типами и приложениями. Его редактирование исправляет проблему, НО такое решение является временным, так как этот файл генерируется при каждом обновлении системы из *.desktop файлов.

Нужно отредактировать MimeType (я его просто закомментировал) в /usr/share/applications/visual-studio-code.desktop и обновить mimeinfo.cache:

$ sudo nano /usr/share/applications/visual-studio-code.desktop
...
# MimeType=text/plain;inode/directory;
...
$ sudo update-desktop-database /usr/share/applications

Enter password to unlock your login keyring

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

Решение:

# можно нажать `Super+A` и поискать приложение `passwords and keys`
$ seahorse &

# Если пакет не установлен
$ yay -S seahorse

image

Удаляем вкладку Login:

image

Другой вариант удалить все кейринги вручную:

$ rm -rf ~/.local/share/keyrings

Далее удаляем настройки Chrome:

$ rm -rf ~/.config/google-chrome

Теперь остается только перезапустить Chrome.

Справка по командам и т.д.

Cheat.sh

Ищет на stackoverflow и других ресурсах справку по командам и языкам программирования.

Установка:

curl https://cht.sh/:cht.sh | sudo tee /usr/local/bin/cht.sh
sudo chmod +x /usr/local/bin/cht.sh

# Так же требуются пакеты xsel и rlwrap
yay -S xsel rlwrap

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

# Интерактивный режим
$ cht.sh --shell <language>
$ cht.sh --shell bash
type 'help' for the cht.sh shell help
cht.sh/bash> for
# shell - Bash 'for' loop syntax?
#
# Replace

for (($i=0...

# with

for ((i=0;i<10;i++))

# [jman] [so/q/6854118] [cc by-sa 3.0]
cht.sh/bash>

$ cht.sh go create file
/*
 * go - Create an empty text file
 *
 * Don't try to check the existence first, since you then have a race if
 * the file is created at the same time. You can open the file with the
 * O_CREATE flag to create it if it doesn't exist:
 */

os.OpenFile(name, os.O_RDONLY|os.O_CREATE, 0666)

// [JimB] [so/q/35558787] [cc by-sa 3.0]

# Небольшой туториал по языку
$ cht.sh python :learn

Marker

Установка:

$ git clone --depth=1 https://github.com/pindexis/marker ~/.marker && ~/.marker/install.py
  • Ctrl-space: search for commands that match the current written string in the command-line.
  • Ctrl-k (or marker mark): Bookmark a command.
  • Ctrl-t: place the cursor at the next placeholder, identified by ‘{{anything}}’
  • marker remove: remove a bookmark

image

Пользовательские команды хранятся в ~/.local/share/marker/user_commands.txt.

Пример:

yay -S {{package}}##install package
yay -S --noconfirm {{package}}##install package without confirmations
yay -Ss {{search}}##search packages
yay -Si {{package}}##package information
yay -Sc##clean
yay -Syu##update all packages
yay -Ps##print system stats
yay -Pu##print list of packages that needs to be updated
yay -Rns {{package}}##remove package
exec "$SHELL"##reload shell

«Встроенные» в /home/sergey/.marker/tldr/.

TLDR

Этим я пользовался до cht.sh.

Получаем краткую справку по команде:

$ tldr nvm
✔ Page not found. Updating cache...
✔ Creating index...

  nvm

  Install, uninstall or switch between Node.js versions.
  Supports version numbers like "0.12" or "v4.2", and labels like "stable", "system", etc.
  Homepage: https://github.com/creationix/nvm.

  - Install a specific version of Node.js:
    nvm install node_version

  - Use a specific version of Node.js in the current shell:
    nvm use node_version

  - Set the default Node.js version:
    nvm alias default node_version

  - List all available Node.js versions and highlight the default one:
    nvm list

  - Uninstall a given Node.js version:
    nvm uninstall node_version

  - Launch the REPL of a specific version of Node.js:
    nvm run node_version --version

  - Execute a script in a specific version of Node.js:
    nvm exec node_version node app.js

Шпаргалка по командам Shell

# ==============================================================================
#
# Основы синтаксиса
#
# ==============================================================================

# $1, $2, $3, ... are the positional parameters.
# "$@" is an array-like construct of all positional parameters, {$1, $2, $3 ...}.
# "$*" is the IFS expansion of all positional parameters, $1 $2 $3 ....
# $# is the number of positional parameters.
# $- current options set for the shell.
# $$ pid of the current shell (not subshell).
# $_ most recent parameter (or the abs path of the command to start the current shell immediately after startup).
# $IFS is the (input) field separator.
# $? is the most recent foreground pipeline exit status.
# $! is the PID of the most recent background command.
# $0 is the name of the shell or shell script.

# присвоить значение переменной
x=42

# Для вывода используем echo и printf
echo "x=$x"
echo "x=${x}"
printf "x=%sn" x

# Если переменная не задана, то присваиваем ей дефолтное значение
x=${x:-default}

# $ { varname :- word }
# If varname exists and isn’t null, return its value; otherwise return word.

# Purpose:
# Returning a default value if the variable is undefined.

# Example:
# ${count:-0} evaluates to 0 if count is undefined.

# $ { varname := word}
# If varname exists and isn’t null, return its value; otherwise set it to word and then return its value. Positional and special parameters cannot be assigned this way.

# Purpose:
# Setting a variable to a default value if it is undefined.

# Example:
# $ {count := 0} sets count to 0 if it is undefined.

# $ { varname :? message }
# If varname exists and isn’t null, return its value; otherwise print varname : followed by message, and abort the current command or script (non-interactive shells only). Omitting message produces the default message parameter null or not set.

# Purpose:
# Catching errors that result from variables being undefined.

# Example:
# {count :?” undefined! " } prints “count: undefined!” and exits if count is undefined.

# $ { varname :+word }
# If varname exists and isn’t null, return word; otherwise return null.

# Purpose:
# Testing for the existence of a variable.

# Example:
# $ {count :+ 1} returns 1 (which could mean “true”) if count is defined.


# $ { varname : offset }
# $ { varname : offset:length }

# Purpose:
# Returning parts of a string (substrings or slices).

# Example:
# If count is set to frogfootman, $ {count :4} returns footman. $ {count :4:4} returns foot.

# Экспорт глобальной переменной
export VAR=42

# Генерация строк с помощью Brace expansion
$ echo a{d,c,b}e
ade ace abe

# Массивы

arr=(Hello World)

echo ${arr[0]} ${arr[1]}

${arr[*]} # Все записи в массиве
${!arr[*]} # Все индексы в массиве
${#arr[*]} # Количество записей в массиве
${#arr[0]} # Длина первой записи (нумерация с нуля)

array=(one two three four [5]=five)

echo "Array size: ${#array[*]}"  # Выводим размер массива

echo "Array items:" # Выводим записи массива
for item in ${array[*]}
do
  printf "   %sn" $item
done

echo "Array indexes:" # Выводим индексы массива
for index in ${!array[*]}
do
  printf "   %dn" $index
done

echo "Array items and indexes:" # Выводим записи массива с их индексами
for index in ${!array[*]}
do
  printf "%4d: %sn" $index ${array[$index]}
done

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

array=("first item" "second item" "third" "item")

echo "Number of items in original array: ${#array[*]}"
for ix in ${!array[*]}
do
  printf "   %sn" "${array[$ix]}"
done
echo

arr=(${array[*]})
echo "After unquoted expansion: ${#arr[*]}"
for ix in ${!arr[*]}
do
  printf "   %sn" "${arr[$ix]}"
done
echo

arr=("${array[*]}")
echo "After * quoted expansion: ${#arr[*]}"
for ix in ${!arr[*]}
do
  printf "   %sn" "${arr[$ix]}"
done
echo

arr=("${array[@]}")
echo "After @ quoted expansion: ${#arr[*]}"
for ix in ${!arr[*]}
do
  printf "   %sn" "${arr[$ix]}"
done

# Циклы

for i in $(seq 1 10);
do
  echo $i
done

for ((i = 0 ; i < max ; i++ ))
do
  echo $i
done

for i in {0..10}
do
  echo $i
done

for w in word1 word2 word3
do
  doSomething($w)
done

# А вот это zsh не умеет!
for filename in *.sh
  echo "$filename"
end

i=0
while (( ++i <= num )); do
  printf 'counter is at %dn' "$i"
done

i=1
while [ "$i" -le "$num" ]; do
  printf 'counter is at %dn' "$i"
  i=$(( i + 1 ))
done

# Условия

if [ "$seconds" -eq 0 ]; then
  timezone_string="Z"
elif [ "$seconds" -gt 0 ]; then
  timezone_string=$(printf "%02d:%02d" $((seconds/3600)) $(((seconds / 60) % 60)))
else
  echo "Unknown parameter"
fi

# В условиях нужно использовать двойные скобки

# [ is just a regular command with a weird name.
# ] is just an argument of [ that prevents further arguments from being used.

# [[ a = a && b = b ]]: true, logical and
# [ a = a && b = b ]: syntax error, && parsed as an AND command separator cmd1 && cmd2just an argument of [ that prevents further arguments from being used.

# x='a b'; [[ $x = 'a b' ]]: true, quotes not needed
# x='a b'; [ $x = 'a b' ]: syntax error, expands to [ a b = 'a b' ]

# Подробнее тут:
#   <https://stackoverflow.com/a/47576482>

# -eq
# is equal to

[ "$a" -eq "$b" ]

# -ne
# is not equal to

[ "$a" -ne "$b" ]

# -gt
# is greater than

[ "$a" -gt "$b" ]

# -ge
# is greater than or equal to

[ "$a" -ge "$b" ]

# -lt
# is less than

[ "$a" -lt "$b" ]

# -le
# is less than or equal to

[ "$a" -le "$b" ]

# <
# is less than (within double parentheses)

(("$a" < "$b"))

# <=
# is less than or equal to (within double parentheses)

(("$a" <= "$b"))

# >
# is greater than (within double parentheses)

(("$a" > "$b"))

# >=
# is greater than or equal to (within double parentheses)

(("$a" >= "$b"))

# <http://tldp.org/LDP/abs/html/comparison-ops.html>

# [ ‒ это всего лишь команда, последним аргументом которой всегда должна быть "]"! Все операторы описаны в man'е:
man [

# Это вполне себе валидное выражение
"[" 1 -eq 0 "]" || echo fail

# Строка слева всегда имя переменной
x=42; [[ "x" -eq "42" ]] || echo fail

# выражение слева всегда переменная

case $VAR in
  foo) ... ;;
  bar) ... ;;
  # Все остальные значения
  *) ... ;;
esac

# Объявление функции
foo() {
  # Аргументы функции
  $1..$N
  # Локальная переменная
  local x=42
  ...
  # Теперь в $1 будет $2, в $2 ‒ $3 и т.д.
  shift
}

# Экспорт функции
export -f foo

die() { echo "$*" 1>&2 ; exit 1; }
...
die "Kaboom"

[ "$#" -eq 2] || die "Needs 2 arguments, input and output"

# The syntax is token-level, so the meaning of the dollar sign depends on the token it's in. The expression $(command) is a modern synonym for `command` which stands for command substitution; it means, run command and put its output here. So

echo "Today is $(date). A fine day."

# Управление выводом

# Направить stdout одной программы в stdin другой
command1 | command2

# Перенаправление stdout и stderr
command1 |& command2

# Создать либо перезаписать файл, добавив строку
command > out

# Создать файл, если его не существует и дописать строку в конец
command >> out

# Направить stderr команды в файл
command 2>&1 out

# stdout 2-ой команды, является stdin для первой
command1 <<< command2

# Вывод многострочного текста
cat <<EOF
хуй
пизда
джигурда
EOF

cat >> /path/to/file <<EOL
хуй
пизда
джигурда
EOL

# ==============================================================================
#
# Написание скриптов
#
# ==============================================================================

# Первой строкой скрипта идет Shebang, торый указывает какой интерпретатор использовать

#!/usr/bin/env bash

# При наличии ошибок прекратит выполнение сценария
set -e

# Так же часто делают каталог скрипта рабочим (по-умолчанию рабочим является тот откуда запустили скрипт)
cd "$(dirname "$0")"

# ==============================================================================
#
# Выполнение скриптов
#
# ==============================================================================

# Сделать файл исполняемым
$ chmod +x /path/to/file

# Выполнит скрипт в текущем процессе (переменные и функции, объявленные внутри скрипта станут доступны в терминале)
$ source /path/to/file

# ==============================================================================
#
# Запуск команд
#
# ==============================================================================

# Запустить процесс и вернуть его дескриптор (при закрытии терминала будет остановлена)
$ command &

# То же самое за исключением того, что процесс не будет остановлен при закрытии терминала
$ nohup command &

# ==============================================================================
#
# Пакеты
#
# ==============================================================================

# Установить пакет
$ yay -S <package>

# Удалить пакет
$ yay -Rns <package>

# Обновить все установленные пакеты
$ yay -Syu

# Обновить в т.ч. с пакетами для разработчика
$ yay -Syu --devel --timeupdate

# Очистить кеш
$ yay -Sc

# Удалить все ненужные зависимости
$ yay -Yc

# Статистика по пакетами
$ yay -Ps

# Generates development package DB used for devel updates
$ yay -Y --gendb

# Ошибки с удалением зависимостей

$ yay -Rns gnome-extra
checking dependencies...
error: failed to prepare transaction (could not satisfy dependencies)
:: nautilus: removing nautilus-sendto breaks dependency 'nautilus-sendto'
$ yay -Rdd nautilus-sendto

# Теперь можно снести gnome-extra

# ==============================================================================
#
# Текст
#
# ==============================================================================

# Замена в тексте
$ echo "This is a test" | sed 's/test/another test/'

# Ключ -e позволяет выполнить несколько команд:
#   sed -e 's/This/That/; s/test/another test/'

# Перевод регистра
$ echo lowercase | tr '[:lower:]' '[:upper:]'
LOWERCASE

# ==============================================================================
#
# Файловая система
#
# ==============================================================================

# Список разделов
$ sudo fdisk -l

$ sudo mkdir /mnt/usb1
# Монтировать устройство
$ sudo mount /dev/sdb1 /mnt/usb1

# Размонтируем устройство
$ sudo umount /dev/sdb1
# или
$ sudo umount /mnt/usb1

# Сменить владельца и группу для файла
$ sudo chown $USER:$USER /path/to/file

# В Linux все файлы. Регулярные файлы ‒ обычные файлы, каталоги ‒ это файлы содержащие список файлов и т.д.

# Перемещение/переименование файла
$ mv <src> <dst>

# Копирование файлов
$ cp <src> <dst>

# Копировать каталог и все вложенные файлы
$ cp -r <src> <dst>

# Полный путь до файла
$ realpath example.txt
/home/username/example.txt

# Листинг каталога
$ ls
$ tldr ls

# Вывести информацию о владельце и группе файла
$ ls -ld /path/to/file
$ stat /path/to/file

# Вывести все вложенные файлы
$ ls -R <path>
$ find <path> -print

# Покажет имя и размер
$ du -a <path>

# Размер всех файлов с расширеним .txt
$ du -chs *.txt

# Создание каталога
$ mkdir <target>

# Создание каталога вместе с родительскими каталогами, если тех не существует
$ mkdir -p <target>

# Создать каталог с определенными правами
$ mkdir -m 0750 <directory>

# Создание множества каталогов
$ mkdir foo bar baz
# или
$ mkdir prefix-{foo,bar,baz}

# Такой же трюк работает при создании файлов
$ touch {foo,bar,baz}.txt

# Создать мягкую ссылку на файл либо заменить ее новой
$ ln -sf path/to/new_file path/to/symlink

# Мягкая ссылка содержит путь до файла. Жесткая ссылается на inode, искомый
# файл при перемещении остается доступен по ссылке и невозможно ссылаться на
# файл на другом устройстве

# Слияние файлов в один
$ paste file1.txt file2.txt > fileresults.txt

# Удалить файлы старше 5 дней
$ find /path/to/files* -mtime +5 -exec rm {} ;

# Удалить все шрифты соответствущие шаблону *powerline* без учета регистра
# «{} ;» rm будет вызван множество раз
# «{} +» добавляет агрументы к rm
$ sudo find /usr/share/fonts -iname "*powerline*" -exec rm {} +

# Поиск фала по имени в специальной базе
$ locate -e login.keyring
/home/sergey/.local/share/keyrings/login.keyring

# Установка
$ yay -S mlocate

# Перед первым запуском следует выполнить
$ sudo updatedb

# После установки будет доступен сервис updatedb.timer, который будет ежедневно обновлять базу

# Стастика
$ locate -S
Database /var/lib/mlocate/mlocate.db:
	157 512 directories
	1 384 522 files
	119 423 666 bytes in file names
	38 722 751 bytes used to store database

# Поиск исполняемых файлов, исходников и страниц манула
$ whereis <q>

# Покажет что куда смонтировано (можно свободное место узнать)
$ df -h --total

# Узнать на каком разделе смонтирован каталог
$ df -h /tmp

# Просмотр числа inode
$ df -i

# Просмотр содержимого фйала с навигацией
$ less /path/to/file

# или более короткая версия в ZSH
$ < /path/to/file

# Просмотр логов в реальном времени
$ tail -f /var/log/syslog | less

# Вывести строки не соответствующие шаблону
$ grep -Pv <exclude_pattern> <filename>

# Создать файл, забитый null-байтами
$ dd if=/dev/zero of=/tmp/nullbytes bs=1M count=1

# Конфертировать .md в .rst
$ pip install m2r
$ m2r --help

# Конвертировать .webp в .png
$ yay -S libwebp
$ dwebp file.webp -o file.png

# Вывод содержимого файла с подсветкой синтаксиса
$ yay -S ccat
$ ccat ./file

# Вывести файлы в каталоге, отсортировав их по времени до доступа
$ ls -ltu <path>

# Изменить размер каталога /tmp
$ mount -o remount,size=4G /tmp/

# Подробная информация о диске
$ sudo smartctl -a /dev/nvme0

# ==============================================================================
#
# Работа с архивами
#
# ==============================================================================

# Заархивировать каталог
$ tar -czvf filename.tar.gz directory

# Для извлечения файлов проще всего пользоваться плагином Oh My ZSH extract

# Извлечь архив и удалить его (ключ -r)
$ extract -r <filename>

# Извлечь .tar.gz
$ tar zxvf <yourfile>.tar.gz -C /usr/src/

# Скачать и Распаковать Архив с помощью WGET
$ wget http://example.com/archive.tar -O - | tar -x
$ wget http://example.com/archive.tar.gz -O - | tar -xz
$ wget http://example.com/archive.tar.bz2 -O - | tar -xj

# Скачать и Распаковать Архив с помощью CURL
$ curl http://example.com/archive.tar | tar -x
$ curl http://example.com/archive.tar.gz | tar -xz
$ curl http://example.com/archive.tar.bz2 | tar -xj

# ==============================================================================
#
# Сеть
#
# ==============================================================================

# Показать все прослушиваемые и установленные порты TCP и UDP вместе с PID
# связанного процесса
$ netstat -plantu

# Все запущенные сервера на хосте
$ netstat -lnt

# Скачать файл в каталог
$ wget -P $ZSH_CUSTOM/themes https://raw.githubusercontent.com/caiogondim/bullet-train-oh-my-zsh-theme/master/bullet-train.zsh-theme

# ==============================================================================
#
# Шрифты
#
# ==============================================================================

# Список установленных шрифтов
$ fc-list

# Обновить базу шрифтов после добавления/удаления их в/из `/usr/share/fonts`
# либо `~/.local/share/fonts`
$ fc-cache -f -v

# ==============================================================================
#
# Буфер обмена
#
# ==============================================================================

$ yay -S xclip

# Скопировать текст в буфер обмена
$ echo 123 | xclip -sel clip

# Копировать содержимое файла в буфер обмена
$ xclip -sel clip < ~/.ssh/github_rsa.pub

# Вывести содержимое буфера обмена
$ xclip -o -sel clip

# Конвертировать файл в base64 и скопировать в буфер обмена
$ file="test.docx"
$ base64 -w 0 $file  | xclip -selection clipboard


# ==============================================================================
#
# Языковые настройки
#
# ==============================================================================

# Список влюченных локалей
$ locale -a

# Добавление локалей

# В этом файле находится список всех поддерживаемых локалей
# Раскомментируем нужную
$ sudo nano /etc/locale.gen

# Генерируем локали
$ sudo locale-gen

# Можно так же локали так добавлять
$ sudo locale-gen de_DE.UTF-8

# Меняем язык системы (нужно перегрузиться)
echo "LANG=de_DE.UTF-8" > /etc/locale.conf

# ==============================================================================
#
# Генерация паролей
#
# ==============================================================================

$ yay -S pwgen
$ pwgen -cnsy 10 1
1u_dr<ZLH;

$ pip install xkcdpass
$ xkcdpass -n 3 -d -
backdrop-unruly-yodel
$ xkcdpass -n 3 -d - --min 2 --max 6
shrank-trio-thong

# ==============================================================================
#
# Прочее
#
# ==============================================================================

# Перегрузить Shell
$ exec "$SHELL"

# Список всех доступных команд
$ compgen -c

# Ищем Chrome
$ compgen -c | grep chrome
google-chrome-stable
chrome-gnome-shell
google-chrome

# Просмотр логов в реальном времени
$ journalctl -f

# Изменить размер терминала
$ gnome-terminal --geometry 135x45

# Документация по командам
$ tldr cat
$ tldr --search create file

Ссылки:

  • Цвет и форматирование текста в консоли;
  • Поиск файлов на Сервере;
  • Файловая система Linux;
  • Inode;
  • Управление разделами LVM;
  • Часто используемые команды Git;
  • Использование регулярных выражений

i3: Введение

i3 – это тайловый оконный менеджер для Linux. Тут настройки под меня.

i3: Установка и настройка

$ yay -S awesome-terminal-fonts bumblebee-status compton fonts-powerline dmenu i3-gaps i3lock-fancy-git lxappearance nitrogen rofi scrot termite xclip
$ sudo nano /usr/share/xsessions/i3-custom.desktop
[Desktop Entry]
Name=i3 custom
Exec=/usr/local/bin/i3-custom
Type=Application
$ sudo nano /usr/local/bin/i3-custom
#!/bin/bash
mkdir -p ~/.config/i3/logs
export TERMINAL=termite
exec i3 -V >> ~/.config/i3/logs/$(date +'%F-%T').log 2>&1
$ sudo chmod +x /usr/local/bin/i3-custom
$ i3-config-wizard
$ cp /etc/xdg/termite/config ~/.config/termite/config
$ nano ~/.config/termite/config
[options]
# ...
font pango:Inconsolata, Font Awesome 10
# ...
[colors]
# ...
# 20% background transparency (requires a compositor)
background = rgba(63, 63, 63, 0.8)
$ cp /etc/xdg/compton.conf ~/.config
$ nano ~/.config/i3/config
# ...
font pango:Droid Sans 10
# ...
# Заменяем все Mod1 на $m и создаем переменную выше вызовов bindsym
set $m Mod1

# lockscreen
bindsym Ctrl+$m+l exec i3lock

# Pulse Audio controls
bindsym XF86AudioRaiseVolume exec --no-startup-id pactl set-sink-volume 0 +5% #increase sound volume
bindsym XF86AudioLowerVolume exec --no-startup-id pactl set-sink-volume 0 -5% #decrease sound volume
bindsym XF86AudioMute exec --no-startup-id pactl set-sink-mute 0 toggle # mute sound

# Sreen brightness controls
bindsym XF86MonBrightnessUp exec xbacklight -inc 20 # increase screen brightness
bindsym XF86MonBrightnessDown exec xbacklight -dec 20 # decrease screen brightness

# Touchpad controls
bindsym XF86TouchpadToggle exec /some/path/toggletouchpad.sh # toggle touchpad

# Media player controls
bindsym XF86AudioPlay exec playerctl play
bindsym XF86AudioPause exec playerctl pause
bindsym XF86AudioNext exec playerctl next
bindsym XF86AudioPrev exec playerctl previous

# rofi
bindsym $m+t exec "rofi -combi-modi window,drun -show combi"

# захватывает весь экран и копирует в буфер обмена
bindsym --release Print exec "scrot /tmp/%F_%T_$wx$h.png -e 'xclip -selection c -t image/png < $f && rm $f'"
# захватывает область экрана и копирует в буфер обмена
bindsym --release Shift+Print exec "scrot -s /tmp/%F_%T_$wx$h.png -e 'xclip -selection c -t image/png < $f && rm $f'"
# ...
bar {
  set $disk_format "{path}: {used}/{size}"
  status_command bumblebee-status -m nic disk:root disk:home cpu memory sensors pulseaudio datetime layout pacman -p root.left-click="nautilus /" root.format=$disk_format home.path=/home home.left-click="nautilus /home" home.format=$disk_format -t solarized-powerline
  position top
}
# ...
# отступы между окнами
gaps outer -10
gaps inner 20

floating_minimum_size 75 x 50
floating_maximum_size -1 x -1
# Убрать рамки у окон:
# 1)
# new_window pixel 0
# 2)
# for_window [class="^.*"] border none
# force floating for all new windows
# for_window [class=".*"] floating enable
for_window [class="Nautilus" instance="file_progress"] floating enable
for_window [class="^Telegram"] floating enable, resize set 800 600
# Всплывающие окна браузера
for_window [window_role="pop-up"] floating enable
# no_focus [window_role="pop-up"]
# прозрачность терминала
exec --no-startup-id compton --config ~/.config/compton.conf
# смена расскладки
exec --no-startup-id setxkbmap -model pc105 -layout us,ru -option grp:ctrl_shift_toggle
# восстановление заставки рабочего стола
exec --no-startup-id nitrogen --restore

Нужно выйти из сессии и выбрать в Display Manager сессию i3 custom.

LXAppearance используется для изменения значков, шрифта по-умолчанию в приложениях.

Nitrogen позволяет менять обои.

Для изменения оформления i3 – служит i3-style:

$ yay -S i3-style
$ i3-style archlinux -o ~/.config/i3/config --reload

XTerm

Вместо Ctrl+Shift+V нужно использовать Shift+Ins, а вместо Ctrl+Shift+CCtrl+C. Права кнопка мыши копировать, клик по колесику – вставить.

Termite: горячие клавиши

Сочетание Значение
ctrl-shift-x activate url hints mode
ctrl-shift-r reload configuration file
ctrl-shift-c copy to CLIPBOARD
ctrl-shift-v paste from CLIPBOARD
ctrl-shift-u unicode input (standard GTK binding)
ctrl-shift-e emoji (standard GTK binding)
ctrl-tab start scrollback completion
ctrl-shift-space start selection mode
ctrl-shift-t open terminal in the current directory [1]_
ctrl-shift-up scroll up a line
ctrl-shift-down scroll down a line
shift-pageup scroll up a page
shift-pagedown scroll down a page
ctrl-shift-l reset and clear
ctrl-+ increase font size
ctrl-- decrease font size
ctrl-= reset font size to default

Отсюда.

Termite: цветовые схемы

$ curl https://raw.githubusercontent.com/khamer/base16-termite/master/themes/base16-nord.config >> ~/.config/termite/config
$ nano ~/.config/termite/config
# 4-ое значение отвечает за прозрачность (1 - непрозрачно, 0 - абсолютная прозрачность)
background          = rgba(40, 44, 52, 0.8)

i3: заставка lockscreen

$ yay -S i3lock-fancy-git
$ nano ~/.config/i3/config
# параметр -B делает фоном lockscreen скриншот экрана с размытием
bindsym Ctrl+$m+l exec i3lock-fancy -gpf Ubuntu -- scrot -z

Репозиторий.

i3: сохранение/восстановление рабочего пространства

# Сохранение
i3-save-tree --workspace 1 > ~/.i3/workspace-1.json
# Восстановление
i3-msg "workspace 1; append_layout ~/.i3/workspace-1.json"

Требует установки зависимостей.

Документация.

Анимированные обои

Видео-инструкция.

Ошибки при установке расширений для Gnome

Посмотрить их можно так:

$ journalctl /usr/bin/gnome-shell -f

Либо можно нажать Alt+F2 и ввести lg и поебаться с консолечкой. Закрыть ее можно с помощью клавиши Esc.

Руководство по установке ArchLinux

ВНИМАНИЕ: С момента публикации данной статьи процесс установки Arch Linux немного изменился. Сверяйтесь с официальной инструкцией, а также обязательно читайте комментарии пользователей ниже, там много интересного и полезного.

Как проходит установка

Установка ArchLinux выполняется из командной строки Live-системы ArchLinux. Вы скачиваете ISO-образ с Live-системой ArchLinux и загружаете его. И из этой Live-системы происходит установка уже на ваш компьютер.

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

В данном руководстве приведено описание процесса установки ArchLinux. Затрагиваются вопросы разметки диска, установки загрузчика Grub, установки среды рабочего стола.

Куда обратиться за помощью

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

Свои вопросы вы также можете оставлять в комментариях к данной статье.

Данное руководство актуально для установки ArchLinux в 2019 году, но, скорее всего, будет актуально и в 2020. Если в установку дистрибутива будут внесены существенные изменения, напишите, пожалуйста, об этом в комментариях.

Подготовка

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

Свободный раздел на диске можно создать средствами текущей операционной системы:

  • В Windows это можно сделать, используя программу Управление компьютером. Обычно ее можно найти через Панель управления: Панель управления→Администрирование→Управление компьютером→Управление дисками.
  • В MacOS можно воспользоваться штатным приложением Дисковая утилита.
  • В Linux можно воспользоваться программой GParted.

Минимальный размер дискового пространства, которое требуется чтобы установить систему, около 1Gb. Конечно, этого будет недостаточно для полноценной установки. Для комфортного пользования рекомендуется, чтобы у вас было около 20Gb свободного места.

Обязательно создайте резервную копию ваших данных.

Скачиваем ArchLinux

Перейдите на страницу Downloads на сайте дистрибутива. Скачайте ISO образ с дистрибутивом (размер файла около 400-500Мб).

Создание LiveUSB/CD

Запишите ISO образ на флешку или CD/DVD-диск. Как это сделать, читайте в статье — Как создать загрузочную флешку или воспользуйтесь программой для записи CD/DVD-дисков.

Загрузка Live-системы

Загрузитесь с созданного на прошлом шаге Live-носителя. Откроется загрузочное меню диска. Выберите пункт «Boot Arch Linux».
ArchLinux Live

Начало установки

Вы попадете в Live-систему ArchLinux. Загрузится виртуальная консоль (терминал), в котором вы будете вводить команды. Во время установки, вы работаете от имени суперпользователя (root).
ArchLinux Live

Раскладка клавиатуры

Добавим русскую раскладку клавиатуры:

loadkeys ru

И загрузим шрифт с поддержкой русского языка:

setfont cyr-sun16

Для переключения между русским и английским языком используется сочетание клавиш Ctrl+Shift.

Подключение к интернет

При установке я использовал проводное подключение по Ethernet. В моем случае установщик автоматически запустил службу dhcpcd и интернет заработал.

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

ping -c 5 archlinux.org

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

iwconfig

Затем воспользуемся утилитой wifi-menu:

wifi-menu имя_интерфейса

Настройка часов

Включите синхронизацию времени через интернет:

timedatectl set-ntp true

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

timedatectl list-timezones

Можно, например, вывести доступные часовые зоны для Европы:

timedatectl list-timezones | grep Europe

Установите ваш часовой пояс:

timedatectl set-timezone Europe/Moscow

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

timedatectl status

Убедитесь, что в поле «Local time» указано верное время.

Разметка диска

Это самый сложный этап для начинающих пользователей. Поэтому, будьте предельно внимательны, чтобы не уничтожить свои данные, если вы устанавливаете ArchLinux, например, рядом с Windows.

Ниже будет много текста, но не пугайтесь, на самом деле все не так сложно, главное внимательно читать и понимать, что вы делаете.

Для разметки диска можно использовать разные утилиты (fdisk, cfdisk, parted и др.). Я воспользуюсь утилитой fdisk.

Я рассмотрю 2 случая:

  • Установка ArchLinux на чистый диск.
    Соответствующий параграф помечен зеленым цветом:
    Разметка диска при установке ArchLinux на чистый диск
  • Установка ArchLinux рядом с другой ОС (например, рядом с Windows или рядом с другим дистрибутивом Linux).
    Соответствующий параграф помечен синим цветом:
    Разметка дисков при установке ArchLinux рядом с другой ОС

Разметка диска при установке ArchLinux на чистый диск

Выведем список дисков и разделов:

fdisk -l

У меня диск пустой. Вывод команды будет примерно следующим:

Disk /dev/sda: 8 GiB, ...
Units: sectors of 1 * 512 = 512 bytes
Sector size...

Отсюда мы можем видеть наш диск /dev/sda размером 8GiB. Этот диск мы и будем размечать. Я создам всего два раздела — корневой раздел и раздел подкачки (swap раздел).

Если у вас достаточный объем оперативной памяти (4-8Gb и более), то можно swap не создавать. К тому же позднее можно настроить, чтобы для swap использовался файл на диске. Но я все равно создам раздел swap для примера.

Итак, мы определили название нашего диска — /dev/sda. Запускаем утилиту fdisk и указываем, что мы хотим работать над диском /dev/sda:

fdisk /dev/sda

Вы попадете в интерактивный режим работы с диском — появится приглашение ко вводу команд «Command (m for help):».
ArchLinux разметка дисков fdisk
Чтобы вывести список доступных команд введите m и нажмите Enter.

Прежде всего создадим новый раздел, который будет использоваться как корневой раздел системы. Вводим n и нажимаем Enter.

Вам будет предложено выбрать тип раздела (Partition type) — первичный (primary) или расширенный (extended). Мы создаем первичный раздел (опция по умолчанию), поэтому просто нажимаем Enter.

Далее нужно ввести номер раздела (Partition number). По умолчанию установлен номер 1, просто нажимаем Enter.

Далее номер первого сектора (First sector). Оставляем значение по умолчанию, просто нажимаем Enter.

На следующем шаге нужно указать номер последнего сектора (Last sector) или размер раздела. У меня диск объемом 8Gb. Из них 1Gb я хочу оставить для раздела swap. Поэтому указываю размер 7Gb. Для этого пишем +7G и нажимаем Enter.
Если вы не планируете создавать раздел swap, то просто нажимаете Enter без ввода размера.

Появится сообщение о том, что создан новый раздел — «Created a new partition 1 of type ’Linux’ and of size 7 GiB» и снова приглашение к вводу новой команды.
ArchLinux разбивка диска

Можно ввести команду p и нажать Enter, чтобы посмотреть в каком состоянии находятся разделы на текущий момент. В нашем случае был создан раздел /dev/sda1:

Создадим второй раздел — раздел swap. Вводим команду n и нажимаем Enter. Для всех параметров будем использовать значения по умолчанию, поэтому на всех шагах просто нажимаем Enter. В итоге мы должны получить сообщение: «Created a new partition 2 of type ’Linux’ and of size 1023 MiB».

Если теперь снова ввести команду p и нажать Enter, то можно увидеть, что у нас создано два раздела /dev/sda1 и /dev/sda2:
Установка ArchLinux разметка дисков

Раздел /dev/sda2 будет использован под swap, поэтому необходимо изменить тип раздела. Для этого вводим команду t и нажимаем Enter. Вводим номер раздела, тип которого мы хотим изменить. В нашем случае вводим 2 и нажимаем Enter. Далее нужно ввести числовой номер, определяющий тип раздела, используем код 82 (это код Linux swap радела). Вводим 82 и нажимаем Enter.
ArchLinux создание Swap раздела

Для просмотра разделов можно снова ввести команду p и нажать Enter (обратите внимание, что раздел /dev/sda2 теперь имеет тип Linux swap):
ArchLinux разметка диска

Теперь важный шаг. На самом деле до этого мы только подготавливали таблицу разделов. Сами разделы на диске еще не созданы. Теперь применим все наши изменения и создадим разделы. Вводим команду w и нажимаем Enter. Утилита fdisk будет закрыта.
ArchLinux создание разделов

Итак, мы создали на диске /dev/sda два раздела /dev/sda1 и /dev/sda2. Раздел /dev/sda1 будет использоваться как корневой раздел, на него и будет устанавливаться система. Раздел /dev/sda2 будет использоваться как раздел подкачки (swap). Чтобы посмотреть какие разделы сейчас созданы, можно ввести команду:

fdisk -l

Выполним форматирование нашего корневого раздела /dev/sda1, для этого выполняем команду:

mkfs.ext4 /dev/sda1

Разметка дисков при установке ArchLinux рядом с другой ОС

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

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

Сначала посмотрим, какие разделы на данный момент у нас на диске. Выполняем команду:

fdisk -l

fdisk

У меня на диске пять разделов — /dev/sda1,2,5,6,7. Раздел /dev/sda1 это расширенный раздел (extended). Внутри этого раздела размещены разделы /dev/sda5,6,7. На этих разделах уже установлен другой дистрибутив Linux (они используются дистрибутивом).

Для MBR первичных разделов на диске может быть всего 4, они всегда имеют номера от 1 до 4. Если раздел имеет номер 5, 6, 7 и т.д, то это уже логический раздел, который находится внутри расширенного раздела. Расширенный раздел это первичный раздел, который не содержит собственной файловой системы, а содержит другие логические разделы. Нельзя создать пять или более первичных разделов.

Меня интересует раздел /dev/sda2. Это первичный раздел (primary). На него я и буду устанавливать ArchLinux. На самом деле у вас такого раздела может и не существовать. У вас может быть просто неразмеченное свободное пространство на диске, которое мы будем использовать для создания нового раздела. Так как у меня раздел уже создан, то я его сначала удалю (хотя это и не обязательно). После удаления данного раздела, мы как раз получим ситуацию, когда на диске появится свободное незадействованное пространство.

Запускаем утилиту fdisk:

fdisk /dev/sda

Сначала я удалю раздел /dev/sda2. Вводим команду d. Вводим номер раздела: 2. Получаем сообщение «Partition 2 has been deleted». Раздел удален, значит у нас появилось свободное неразмеченное пространство на диске, которое мы будем использовать для создания нового раздела.

Вводим команду n, чтобы создать новый раздел. Все предлагаемые настройки оставляем по умолчанию (первичный раздел, номер раздела 2), то есть просто нажимаем Enter. Мне еще был задан вопрос «Do you want to remove the signature?», я ввел y.

Мы создали раздел /dev/sda2, который будет использоваться для установки ArchLinux. Запишем изменения, для этого вводим команду w.

Отформатируем только что созданный раздел. Выполняем команду:

mkfs.ext4 /dev/sda2

Обращаю внимание на то, что я не создал раздел swap, так как данный раздел у меня уже создан, он имеет название /dev/sda7. Процесс создания swap раздела был описан выше в параграфе «Разметка диска при установке ArchLinux на чистый диск».

Очень важно. Далее по тексту производится установка ArchLinux на раздел /dev/sda1 (это случай, который был рассмотрен выше в параграфе «Разметка диска при установке ArchLinux на чистый диск»). Вместо /dev/sda1 вы должны использовать свой раздел, то есть, если это /dev/sda2, который мы только что создали, то вместо /dev/sda1 вы должны писать /dev/sda2. Аналогично и с инициализацией swap раздела (см. следующий параграф). При инициализации swap раздела вместо /dev/sda2 я в данном случае должен подставить /dev/sda7 (так как именно этот swap раздел у меня уже был создан). Будьте предельно внимательны, не запутайтесь.

Инициализация swap

Если во время разметки диска вы создали раздел подкачки, или же он уже был на вашем диске, то его необходимо инициализировать. Выполняем команды (/dev/sda2 — это раздел подкачки):

mkswap /dev/sda2
swapon /dev/sda2

Монтирование разделов

Примонтируем наш корневой раздел /dev/sda1 в директорию /mnt:

mount /dev/sda1 /mnt

Выбор серверов-зеркал

Во время установки из интернета скачиваются пакеты. Пакеты размещаются на серверах-зеркалах.

Можно выбрать географически ближайший к вам сервер, чтобы загрузка пакетов происходила быстрее. Для этого нужно отредактировать файл /etc/pacman.d/mirrorlist. В этом файле представлен список серверов. Чем выше в списке расположен сервер, тем выше его приоритет, поэтому ближайший к вам сервер желательно переместить наверх списка.

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

Откройте файл /etc/pacman.d/mirrorlist для редактирования:

nano /etc/pacman.d/mirrorlist

Мы открыли файл в консольном редакторе nano. Я перенес сервер от Яндекс (это строка «Server = http://mirror.yandex.ru/archlinux/$repo/os/$arch») наверх списка.

Чтобы это сделать, найдите в списке сервер от Яндекса и поставьте на эту строку курсор. Нажмите сочетание клавиш Ctrl+K чтобы вырезать строчку. Теперь переместите курсор в самый верх файла и нажмите сочетание Ctrl+U, чтобы вставить строчку.

Сохраните изменения в файле и закройте редактор. Для этого нажмите Ctrl+X, нажмите y, а затем Enter.

Установка основных пакетов системы

Подготовительная часть окончена. Теперь можно выполнить установку основных пакетов base, для этого выполните команду:

pacstrap /mnt base

Процесс установки пакетов займет некоторое время.

У меня во время установки пакетов промелькнула вот такая ошибка: [ 1859.596408] systemd-tmpfiles[4216]: Failed to create file /sys/devices/system/cpu/microcode/reload: Read-only filesystem, но она никак не повлияла на дальнейшую установку. Поэтому я ее просто проигнорировал.

Генерация файла fstab

Сгенерируем файл fstab:

genfstab -L /mnt >> /mnt/etc/fstab

Просмотреть содержимое файла можно командой:

cat /mnt/etc/fstab

Изменение корневого каталога

Воспользуемся скриптом arch-chroot, чтобы сменить корневой каталог. Мы переключимся на каталог /mnt, в который у нас примонтирован корневой раздел диска.

arch-chroot /mnt

Часовой пояс

Настроим часовой пояс:

ln -sf /usr/share/zoneinfo/Europe/Moscow /etc/localtime

Выполним hwclock, чтобы сгенерировать файл /etc/adjtime, в котором хранятся соответсвующие настройки.

hwclock --systohc

Локализация

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

Для поддержки русского и/или других языков необходимо раскомментировать соответствующие строки (локали) в файле /etc/locale.gen. Откройте файл для редактирования:

nano /etc/locale.gen

Я раскомментировал строки:

en_US.UTF-8 UTF-8
ru_RU.UTF-8 UTF-8

Сохраните изменения и закройте файл.

Теперь генерируем локали. Для этого выполняем команду:

locale-gen

Установим переменную LANG в файле /etc/locale.conf. Создадим файл /etc/locale.conf (используем редактор nano):

nano /etc/locale.conf

Введите текст:

LANG=ru_RU.UTF-8

Сохраните и закройте файл.

Также добавим русскую раскладку клавиатуры для консоли и шрифт с поддержкой кириллицы:

nano /etc/vconsole.conf

Введите строки:

KEYMAP=ru
FONT=cyr-sun16

Сохраните и закройте файл.

Настройка hostname и hosts

Создадим файл hostname, в котором введем имя компьютера.

nano /etc/hostname

Вводим имя компьютера, например:

pingvinus

Сохраните и закройте файл.

Отредактируем файл /etc/hosts.

nano /etc/hosts

Содержимое файла должно иметь вид (вместо pingvinus укажите ваш hostname):

127.0.0.1 localhost
::1 localhost
127.0.1.1 pingvinus.localdomain pingvinus

Если у системы постоянный IP-адрес, то вместо 127.0.1.1 укажите этот адрес.

Пароль суперпользователя

Установим пароль суперпользователя (пароль пользователя root). Выполняем команду:

passwd

Вводим пароль и подтверждение пароля.

Установка загрузчика GRUB

Примечание. Если вы устанавливаете ArchLinux рядом с другим дистрибутивом Linux, и у вас уже установлен GRUB, то вы можете его использовать, а не устанавливать еще один GRUB на другой раздел. В таком случае вам нужно примонтировать раздел, на котором уже установлен GRUB, выполнить chroot на данный раздел и запустить update-grub.

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

mkdir /mnt2 - создаем директорию, в которую будем монтировать раздел, на котором уже установлен GRUB.
mount /dev/sda5 /mnt2 - монтируем раздел.
cd /mnt2 - Входим в директорию.
ls - Проверяем, то ли мы примонтировали.
arch-chroot /mnt2 - Делаем chroot на /mnt2
sudo update-grub
exit
cd ..

Если же вам нужно установить и настроить GRUB, то следуйте указаниям ниже.

Установим загрузчик GRUB.

Сначала установим пакет grub, для этого выполняем команду:

pacman -S grub

Если вы используете или планируете использовать на этом компьютере не только ОС Linux, но и другие операционные системы, например, Windows, то установите пакет os-prober:

pacman -S os-prober

Теперь инсталлируем grub:

grub-install /dev/sda

Обратите внимание на то, что в команде мы указываем устройство (/dev/sda), а не раздел. Загрузчик устанавливается в каталог /boot.
Если команда выполнится без ошибок, то вы получите сообщение вида: Installation finished. No error reported.

Запускаем автоматическую настройку grub:

grub-mkconfig -o /boot/grub/grub.cfg

У меня в процессе выполнения данной команды выскочило предупреждение: WARNING: failed to connect to lvmetad: No such file or directory. Falling back to internal scanning. В руководстве по ArchLinux сказано, что это нормально и данное сообщение можно проигнорировать.

Перезагрузка компьютера

Выйдите из окружения chroot, выполнив команду:

exit

Перезагрузите компьютер, выполнив:

reboot

Не забудьте извлечь Live-носитель, чтобы опять случайно не загрузиться в Live-систему.


Второй этап: настройка ArchLinux

После перезагрузки компьютера, вы попадете в свою новую свежеустановленную систему. Перед вами появится консоль и запрос на ввод login’а. Введите root и затем пароль, который вы задали для суперпользователя на этапе установки.

ArchLinux сразу после установки

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


Создание пользователя

Сейчас вы работаете от имени пользователя root. Создадим обычного пользователя, от имени которого вы и будете пользоваться системой. Я создал пользователя pingvinus (вместо pingvinus укажите имя вашего пользователя).

useradd -m -g users -G wheel -s /bin/bash pingvinus

Теперь в директории /home появится домашняя директория пользователя. Ее можно посмотреть командой ls:

$ ls /home
pingvinus

Зададим пароль для только что созданного пользователя:

passwd pingvinus

Настройка интернет

У меня используется проводное Ethernet соединение. IP адрес система получает автоматически. Поэтому необходимо включить сервис DHCP. Выполняем команды:

systemctl enable dhcpcd.service
systemctl start dhcpcd.service

Ждем несколько секунд пока система получит IP-адрес. Можно проверить соединение, выполнив ping:

ping -c 5 archlinux.org

Установка sudo

Установим sudo и позволим нашему пользователю использовать sudo.

Для установки sudo выполните команду:

pacman -S sudo

Теперь разрешим пользователям группы wheel использование sudo. Когда мы создавали пользователя, то мы добавили его в группу wheel, поэтому он сможет пользоваться sudo. Выполняем команду:

visudo

Откроется редактор Vi с файлом настроек sudo.

Найдите строку «# %wheel ALL=(ALL) ALL» (перемещайте курсор вниз клавишей Стрелка Вниз. Строка закомментирована (перед ней стоит символ решетки #).
visudo

Нам нужно раскомментировать ее (то есть удалить символ решетки). Поместите курсор на символ решетки и нажмите клавишу x. Также можно удалить пробел, который стоял после решетки.
visudo wheel

Теперь нужно сохранить изменения и закрыть редактор. Для этого нажмите двоеточие «:», в нижней части экрана появится строка для ввода символов. Введите wq и нажмите Enter. Если вдруг вы не хотите сохранять изменения, а хотите просто закрыть редактор, то вместо wq введите q!.
visudo сохранить

Установка Иксов

Прежде всего установим «иксы» — Xorg. Выполняем команду:

pacman -S xorg

Вас спросят, устанавливать ли все пакеты, я устанавливал все, просто нажмите Enter.

Установка экранного менеджера

Экранный менеджер запускается сразу после загрузки системы. В нем вы выбираете пользователя для входа в систему и вводите пароль. Существует несколько разных экранных менеджеров, я устанавливал LightDM:

pacman -S lightdm lightdm-gtk-greeter

Разрешим автоматический запуск lightdm при загрузке системы:

systemctl enable lightdm.service

Установка графического окружения

В качестве графического окружения для ArchLinux доступно множество сред рабочего стола и оконных менеджеров. Выбор зависит только от вас. Ниже я для примера покажу, как установить Gnome, XFCE, KDE, Mate и Cinnamon. За подробностями обращайтесь к официальному Wiki или пишите комментарии с вопросами под этим материалом.

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

Теперь установим среду рабочего стола. Вы можете установить одну или несколько сред рабочего стола. Если вы новичок, то рекомендую начать, например, с XFCE.

Установка Gnome

Установим Gnome. Я устанавливал два пакета — gnome и gnome-extra. Второй пакет содержит несколько дополнительных программ для Gnome (архиватор, текстовый редактор, несколько вспомогательных утилит, игры и так далее.

pacman -S gnome gnome-extra

Установка займет некоторое время, так как пакетов в Gnome очень много.

Установка XFCE

Для установки XFCE выполните команду:

sudo pacman -S xfce4 xfce4-goodies

Установка KDE

Для установки KDE выполните команду:

sudo pacman -S plasma

Установка Mate

Для установки Mate выполните команду:

sudo pacman -S mate mate-extra

Установка Cinnamon

Для установки Cinnamon выполните команду:

sudo pacman -S cinnamon

Перезагружаем компьютер

Итак, вы установили среду рабочего стола. Второй этап установки ArchLinux завершен. Можно перезагрузить компьютер и проверить работу. Перезагружаем компьютер, выполнив команду:

reboot

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

Выберите пользователя и введите пароль. Загрузится рабочий. Например, KDE будет выглядеть примерно так:
ArchLinux установка KDE

Что дальше?

Вы установили ArchLinux и установили среду рабочего стола! Теперь можно пользоваться системой.

Шрифт в терминале

Если вдруг у вас в терминале ужасный шрифт, то установите пакет ttf-dejavu и перезапустите терминал:

sudo pacman -S ttf-dejavu

Обновление системы:

sudo pacman -Syu

Установка пакетов.

Для установки пакетов используется команда pacman -S имя_пакета. Например, для установки браузера Firefox выполните:

sudo pacman -S firefox

Установка AUR, установка Yaourt

Репозиторий AUR (Arch User Repository) это репозиторий для ArchLinux, поддерживаемый сообществом. Он содержит огромное количество пакетов, которые устанавливаются путем компиляции из исходных кодов. Многие пакеты, которые есть в официальном репозитории ArchLinux, изначально были в репозитории AUR. AUR содержит очень много полезных приложений, которых нет в официальном репозитории.

Для установки пакетов из AUR используется утилита Yaourt. Раньше Yaourt можно было установить из стороннего репозитория archlinuxfr, но потом владелец репозитория удалил оттуда пакет yaourt. Поэтому мы установим Yaourt прямо из AUR.

Установим Yaourt. Выполните в терминале последовательно следующие команды:

sudo pacman -S git base-devel
git clone https://aur.archlinux.org/package-query.git
cd package-query/
makepkg -si
cd ..
git clone https://aur.archlinux.org/yaourt.git
cd yaourt
makepkg -si
cd ..
sudo rm -dR yaourt/ package-query/

Теперь можно устанавливать пакеты из AUR с использованием команды yaourt.

Для установки пакета используется команда:

yaourt -S имя_пакета

Для удаления пакета:

yaourt -Rs имя_пакета

Для обновления пакетов:

yaourt -Syu

Заключение

ArchLinux это дистрибутив не для новичков. Если вы прошли все этапы и смогли запустить рабочий стол, то это уже большой шаг. Впереди еще много интересного, настройкой ArchLinux можно заниматься бесконечно.

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

If you ask a group of developers what Linux is, most of them will probably say it’s an open-source operating system. Those with more technical knowledge will probably call it a kernel.

For me, though, Linux is not just an operating system or a kernel. For me, it’s freedom. The freedom of putting together an operating system according to my needs, and that’s where Arch Linux comes in.

According to their wiki,

Arch Linux is an independently developed, x86-64 general-purpose GNU/Linux distribution that strives to provide the latest stable versions of most software by following a rolling-release model.

The default installation is a minimal base system, configured by the user to only add what is purposely required.

In other words, Arch Linux is a distribution optimized for x86-64 architecture targeted at experienced Linux users. It lets you have full responsibility and control over your system.

You’ll get to choose what packages you want, the kernel (yes there are multiple), the boot-loader, the desktop environment, and so on.

Have you ever heard someone say,

Oh – by the way, I use Arch Linux!

This is because installing Arch Linux on a machine requires you to have proper knowledge of how different parts of a Linux distribution work. So running Arch Linux on your system is kind of a testament to your understanding of Linux.

Speaking from experience, installing Arch Linux is not very different from installing something like Fedora or Ubuntu. It’s just that you have to go through the individual steps manually instead of having an installer do the things for you. But once you’ve gone through the process, you’ll start to understand how the other distributions work in general.

In this article, I’ll walk you through the entire process of installing and configuring Arch Linux on your machine. I’ll also discuss some common tasks and troubleshooting tips near the end.

So come with me and I’ll show you how deep the rabbit hole goes.

Table of Contents

  • Some Assumptions I’m Making
  • How to Create a Bootable Arch Linux USB Drive
  • How to Prepare Your Computer for Installing Arch Linux
  • How To Install Arch Linux
    • How To Set the Console Keyboard Layout and Font
    • How To Verify the Boot Mode
    • How To Connect to the Internet
    • How To Update the System Clock
    • How To Partition the Disks
    • How To Format the Partitions
    • How To Mount the File Systems
    • How To Configure the Mirrors
    • How To Install Arch Linux Base System
  • How To Configure Arch Linux
    • How To Generate the Fstab File
    • How To Login to The Newly Installed System Using Arch-Chroot
    • How To Configure the Time Zone
    • How To Configure the Localization
    • How To Configure the Network
    • How To Set the Root Password
    • How To Create a Non-root User
    • How To Install Microcode
    • How To Install and Configure a Boot Loader
  • How To Install Xorg
  • How To Install Graphics Drivers
  • How To Install a Desktop Environment
    • How To Install GNOME
    • How To Install Plasma
  • How To Finalize The Installation
  • How To Switch Between Desktop Environments
  • How To Manage Packages Using Pacman
    • How To Install Packages Using Pacman
    • How To Remove Packages Using Pacman
    • How To Upgrade Packages Using Pacman
    • How To Search for Packages Using Pacman
  • How To Use AUR in Arch Linux
    • How To Install Packages Using a Helper
    • How To Install Packages Manually
  • How To Troubleshoot Common Problems
  • How To Use the Live Arch ISO as a Rescue Media
  • Further Reading
  • Conclusion

Some Assumptions I’m Making

Before I jump into the core of the tutorial, I want to clarify a few things. To make this entire article approachable, I’m making the following assumptions about you and your system:

  • You know about Arch Linux at a basic level
    • Arch Linux
    • Frequently asked questions
    • Arch compared to other distributions
  • Your computer is using UEFI and not BIOS
  • You have a USB drive large enough (4GB) to boot Linux from
  • You have some previous experience installing Linux (Ubuntu/Fedora)
  • You have enough space to install linux on your HDD or SSD

That’s pretty much it. If you have all of the above, you’re good to go.

How to Create a Bootable Arch Linux USB Drive

To download Arch Linux, head to https://archlinux.org/download/ and download the latest release (2022.01.01 as of this writing). The ISO should be around 870 megabytes in size.

Once downloaded, you’ll need to put it in your USB. You can use the Fedora Media Writer program to do that. Download and install the application on your system. Now connect your USB drive and open the application:

image-48

Click on «Custom image» and use the file browser to pick the downloaded Arch Linux ISO file.

image-49

The application will now let you pick one of your connected USB drives. Be very careful in selecting the right one if you have multiple USB drives connected to your machine. Now hit the «Write to Disk» button and wait until the process is finished.

How to Prepare Your Computer for Installing Arch Linux

In this step you’ll have to make a few changes to your system, otherwise Arch Linux may fail to boot or run properly.

The first change that you’ll have to make is disabling secure boot in your UEFI configuration. This feature helps prevent malware attacks during boot but it also prevents the Arch Linux installer from booting.

Detailed instructions on how you can disable this vary depending on your motherboard or laptop brand. You’ll have to search the internet yourself to find the right way this time.

The second thing that you should disable is only relevant if you’re installing Arch Linux alongside Windows. There is a Windows feature called fast startup that reduces the boot time of your computer by partially hibernating it.

This is generally a nice feature to have but it prevents any other operating system in a dual boot configuration from accessing the hard disk in the process.

To disable this feature, open the start menu and search for «Choose a power plan» as follows:

choose-a-power-plan

Then on the next window, click on «Choose what the power buttons do» from the left sidebar:

image-54

Then on the next window you’ll see a list of «Shutdown settings» and the «Turn on fast startup (recommended)» option should be shown as read only there.

image-55

Click the «Change settings that are currently unavailable» at the top and you should then be able to change the settings.

image-56

Untick the «Turn on fast startup (recommended)» option and press the «Save changes» button at the bottom. From now on the boot process may take a few moments extra but it’s all worth it.

In this article, I’ll install Arch Linux as my default operating system. So I’ll allocate my entire disk space to it.

If you’re trying to install it alongside Windows, however, I have a dedicated article on the topic. And in that article, there is a section that discusses the partitioning process in great detail.

How To Install Arch Linux

Assuming that you have a bootable USB drive and your computer is configured properly, you’ll have to boot from the USB drive. The process of booting from a USB drive differs from machine to machine.

On my machine, hitting the F12 key during boot takes me to the list of bootable devices. From there I can pick my bootable USB drive. You may already know the appropriate technique for your computer or you may have to research a bit.

Once you’ve managed to land on the list of connected bootable devices, select your USB drive to boot from and the following menu should show up:

VirtualBox_archlinux-2022.01.01-x86_64_12_01_2022_18_39_29

Choose the first one from the list and wait until the Arch installer finishes booting up. Once fully booted up, you’ll see something like this:

VirtualBox_archlinux-2022.01.01-x86_64_12_01_2022_18_50_39

That’s it. That’s all you’ll get. Unlike other operating systems that you maybe familiar with, the Arch installer doesn’t have any graphical user interface to automate the installation.

It rather requires you to invest your time and effort and configure each part of the distribution piece by piece. It may sound daunting but, to be honest, if you understand what you’re doing, installing Arch Linux is quite fun.

How To Set the Console Keyboard Layout and Font

As I’ve already said, the Arch installer doesn’t have a graphical user interface so there’s going to be a lot of typing. Configuring your keyboard layout and a nice looking font can make the installation process a lot less frustrating.

By default, the console assumes that you have a standard US keyboard layout. This should be fine for most people but just in case if you happen to have a different one, you can change to that.

All the available keymaps are usually kept inside the /usr/share/kbd/keymaps directory in the form of map.gz files. You can see the list of them by using the ls command:

ls /usr/share/kbd/keymaps/**/*.map.gz

This will list out all the available key maps:

VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_15_58_28-1

Now for example, if you have the Mac-US keyboard layout, locate the corresponding map.gz file from this list which is the mac-us.map.gz one.

You can use the loadkeys command to load the desired keymap. To set mac-us.map.gz as default, execute the following command:

loadkeys mac-us

You can also change the console font if you don’t like the default one. Just like the keymaps, the console fonts are kept inside the /usr/share/kbd/consolefonts which you can list out using the ls command:

ls /usr/share/kbd/consolefonts

This will list out all the available fonts:

VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_16_08_01

You can now use the setfont command for setting one of these. For example, if you want to set the drdos8x16 as default, execute the following command:

setfont drdos8x16

Both the loadkeys and setfont commands are part of the kbd package containing essential Linux keyboard tools. They have great documentation so if you’d like to learn more, feel free to check it out.

How To Verify the Boot Mode

Now that you have your console configured, the next step is to make sure that you’ve booted in UEFI mode and not in BIOS mode.

To be honest, this step seems unnecessary to me since it literally says x86_64 UEFI in the live boot menu. But let’s do it for the sake of the official Arch installation guide.

To verify the boot mode, execute the following command:

ls /sys/firmware/efi/efivars

If you’re in UEFI mode then, it will list out a bunch of files on your screen:

VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_17_18_34

In case of a BIOS boot, the efi directory won’t even exist inside the /sys/firmware directory. If you’re in UEFI mode, (which you should be if you’ve followed everything properly) continue to the next step.

How To Connect to the Internet

Unlike a lot of other live distributions, the Arch live environment doesn’t come with all necessary packages built into it. It contains a number of bare minimum packages that you can use to install the rest of the system. So, a working internet connection is a must.

If you’re using a wired network then you should have a working internet connection from the get go. To test it out, ping any of the public addresses out there:

VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_17_40_04

I’m making these screenshots using VirtualBox, so the internet connection works perfectly with the wired connection. But if you have a wireless connection, things can get a bit tricky.

The live environment comes with the iwd or iNet wireless daemon package. You can use this package to connect to a nearby wireless network.

To begin with, execute the following command:

iwctl

This will start an interactive prompt as follows:

VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_17_59_34

Now execute the following command to see the list of available wireless devices:

device list

This will spit out a list of available wireless devices. By wireless devices I mean any wireless adapter connected to your computer. Let’s assume wlan0 is the device name.

To scan for nearby wireless networks using the found device, execute the following command:

# station <device> scan

station wlan0 scan

You may think that this command will print out a list of all the nearby networks, but that’s not the case. To see the list of networks, execute the following command:

# station <device> get-networks

station wlan0 get-networks

Now assuming the name of your home network is called Skynet, you can connect to it by executing the following command:

# station <device> connect <SSID>

station wlan0 connect Skynet

The iwctl program will prompt you for the wi-fi password. Put it in carefully and, once connected to the network, exit the program by writing exit and hitting enter. Try pinging a public address once again and make sure that the internet is working fine.

How To Update the System Clock

In Linux, NTP or Network Time Protocol is used for synchronizing computer system clocks over a network. You can use the timedatectl command to enable NTP on your Arch live environment:

timedatectl set-ntp true

This command will start outputting some output and after a few seconds. If you do not see the command cursor show up again, try pressing Enter. I’ve faced this inconvenience a few times in the past.

How To Partition the Disks

This is probably the most sensitive step of the entire installation process – because if you mess up your partitions, you lose your precious data. So my advice would be to not immediately follow along with this section. Instead, read the whole section first and then follow along.

To begin the partitioning process, you’ll have to first know about the different disks connected to your computer. You can use fdisk which is a dialog-driven program for creation and manipulation of partition tables.

fdisk -l

This command will list the partition tables for all the available devices on your computer.

VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_19_53_34

As you can see, there are two devices connected to my computer (virtual machine actually). Depending on the number of devices you have, this list can be longer so ignore any device ending with rom, loop, or airoot when reviewing the list. You can not use those devices for the installation.

So that leaves us with the /dev/sda device. Keep in mind that this can be completely different on your machine. For example, if you have an NVME drive, you may see /dev/nvme0n1 instead.

Once you’ve decided which device to use, it’s a good idea to check if there are any existing partitions inside that device. To do so, you can use the following variation of the same fdisk command:

fdisk /dev/sda -l

Remember to replace /dev/sda with what you have. This command will list out all the partitions inside the given device.

VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_20_13_14

Although there are no partitions in this device, in a real life situation you may have previously created partitions. Those partitions will show up as /dev/sda1, /dev/sda2 or in the case of a NVME drive /dev/nvme0n1p1, /dev/nvme0n1p2 and so on.

The fdisk program can do a lot more than just listing partitions. Consult the corresponding ArchWiki page to know about the tasks you can perform using this program.

There is another program cfdisk which is a curses- (programming library) based disk partition table manipulator for Linux. It’s similar in functionality with fdisk but being curses-based means it has an interface which makes it easier to work with.

Execute the following command to start cfdisk on your preferred device:

cfdisk /dev/sda

Remember to replace /dev/sda with what you have. If the device has a previously created partition table, then cfdisk will directly show the list of partitions. Otherwise you’ll get to choose a partition table type to begin with:

VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_20_22_55

Choose gpt for your UEFI based system. Next, you’ll land on the list of partitions and free space on the device:

VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_20_24_09

You can move vertically along the list of devices using your up/down arrow keys and move horizontally along the different actions using the left/right arrow keys.

To install Arch, or any other Linux distribution, you’ll need three separate partitions. They are as follows:

  • EFI system partition – for storing files required by the UEFI firmware.
  • ROOT – for installing the distribution itself.
  • SWAP – for serving as the overflow space for your RAM.

Make sure the right partition/free space is highlighted in the list and select the [ New ] action.

VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_20_37_04

Put the desired partition size. You can use M to denote megabytes, G for gigabytes, and T for terabytes.

For an EFI system partition, you should allocate at least 500MB. Once you’ve put your desire size, press Enter to finalize. The updated list of partitions may look as follows:

VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_20_37_29

The EFI system partition is a special type of partition. It has to be in a specific type and format. To change the default type, keep the newly created partition highlighted and select [ Type ] from the list of actions.

VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_20_39_24

From this long list of types, highlight EFI System and press Enter. The type of the partition in the list should update accordingly:

VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_20_40_37

Next is the root partition. Highlight the remaining free space and select [ New ] once again. This time assign 10GB to this partition. The ideal size of the root partition depends on your necessities. Personally I allocate at least 100GB to the root partition of all my Linux installations.

You don’t need to change the type of this partition. The default Linux filesystem will do.

VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_20_43_14

Create one last partition with the remaining space and change its type to Linux swap from the menu:

VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_20_45_57

The ideal size of a swap partition is a matter of debate. Personally I don’t have swap partitions on my machines. The amount of physical RAM I have is more than enough. But if I ever feel the need for one later on, I use a swapfile instead. Anyways, the final state of your device should be as follows:

VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_20_48_49

If you’re happy with the set-up, highlight [ Write ] from the action list and hit Enter. The program will ask whether you want to persist these changes or not. You’ll have to write yes and press enter if you agree. Once the partition table has been altered, select [ Quit ] to exit from the program.

One thing that I would like to mention for those trying to install Arch Linux alongside Windows is, in that case, the EFI system partition should already exist in your device. So don’t touch that. Just create the other partitions and move on.

How To Format the Partitions

Now that you’ve created the necessary partitions, you’ll have to format them accordingly. You can use the mkfs and mkswap programs to do that. Before the formatting, take a final look at your partition list by executing the following command:

fdisk /dev/sda -l

This time you’ll see the three newly created partitions with their details:

VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_21_02_23

Take note of the device names, like /dev/sda1, /dev/sda2, /dev/sda3 and so on. The EFI system partition has to be in FAT32 format. Execute the following command to format a partition in FAT32 format:

mkfs.fat -F32 /dev/sda1

The next one is the root partition. It can be in a number of formats, but I prefer using EXT4 for all of my Linux filesystems. Use the following command to format the partition in EXT4:

mkfs.ext4 /dev/sda2

This operation may take a few moments to finish depending on your partition size. Finally, the swap partition. Use the following command to format that:

mkswap /dev/sda3

With that, you’ve finished the process of preparing your partitions for the installation.

How To Mount the File Systems

Now that you’ve created and formatted your partitions, you’re ready mount them. You can use the mount command with appropriate mount points to mount any partition:

# mount <device> <mount point>

mount /dev/sda2 /mnt

I hope you remember that the /dev/sda2 partition was created to be the root partition. The /mnt mount point in Linux is for mounting a storage device temporarily. As we only need to mount the partition for installing Arch Linux on it, the /mnt mount point is perfect.

In the case of a swap partition, you won’t mount it like the other ones. You’ll have to tell Linux to use this partition as swap explicitly. To do so, execute the following command:

swapon /dev/sda3

As you may have guessed, the swapon command tells the system to swap on this device. We’ll work with the EFI system partition in a later section. For now, mounting these two partitions will suffice.

How To Configure the Mirrors

There is one last step before you can install Arch Linux on your machine, and that is configuring the mirrors. Mirrors are servers located at different pointes around the world for serving the nearby population.

The installer comes with Reflector, a Python script written for retrieving the latest mirror list the Arch Linux Mirror Status page. To print out the latest mirror list, simply execute the following command:

reflector

If you have a slow internet connection, you may encounter an error message as follows:

failed to rate http(s) download (https://arch.jensgutermuth.de/community/os/x86_64/community.db): Download timed out after 5 second(s).

This happens when the default timeout (5 seconds) is lower than the actual time it’s taking to download the information.

You can remedy to this problem by using the --download-timeout option:

reflector --download-timeout 60

Now reflector will wait for a whole minute before starting to scream. A long list of mirrors should show up on your screen:

VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_21_36_15-1

Going through the entire list to find nearby mirrors would be a pain. That’s why reflector can do that for you.

Reflector can generate a list of mirrors based on a plethora of given constraints. For example, I want a list of mirrors that were synchronized within the last 12 hours and that are located either in India or Singapore (these two are closest to my location), and sort the mirrors by download speed.

Turns out, reflector can do that:

reflector --download-timeout 60 --country India,Singapore --age 12 --protocol https --sort rate

The found servers will be listed like before:

VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_21_45_25

Printing out a mirror list like this is not enough. You’ll have to persist the list in the /etc/pacman.d/mirrorlist location. Pacman, the default package manager for Arch Linux, uses this file to learn about the mirrors.

Before overwriting the default mirror list, make a copy of it:

cp /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.bak

Now execute the reflector command with the --save option as follows:

reflector --download-timeout 60 --country India,Singapore --age 12 --protocol https --sort rate --save /etc/pacman.d/mirrorlist

This command will generate the mirror list and overwrite the default one. Now you’re ready to install the base Arch Linux system.

How To Install Arch Linux Base System

Before installing the base system, it’s a good idea to update the package cache according to the new mirror list. To do so, execute the following command:

pacman -Sy

The pacman program to Arch Linux is what apt is to Ubuntu or dnf is to Fedora. The -S option means sync which is equivalent to install in apt or dnf package managers.

Once the update process is finished, you can use the pacstrap script to install the Arch Linux system. Execute the following command to start the installation process:

pacstrap /mnt base base-devel linux linux-firmware sudo nano ntfs-3g networkmanager

The pacstrap script can install packages to a specified new root directory. As you may remember, the root partition was mounted on the /mnt mount point, so that’s what you’ll use with this script. Then you’ll pass the package names you want to install:

  • base – Minimal package set to define a basic Arch Linux installation.
  • base-devel – Group of packages required for building software from source.
  • linux – The kernel itself.
  • linux-firmware – Drivers for common hardware.
  • sudo – You want to run commands as root right?
  • nano – A pico editor clone with some enhancements.
  • ntfs-3g – NTFS filesystem driver and utilities required for working with NTFS drives.
  • networkmanager – Provides detection and configuration for systems to automatically connect to networks.

I would like to clarify that this list of seven packages is not something mandatory. To have a functional Arch Linux installation, you just need the base, linux, and linux-firmware packages. But considering you’ll need the other ones anyway, why not catch ’em all in one go.

Depending on your internet connection, the installation process may take a while. Sit back and relax until pacstrap does its thing. Once it’s done, you’ll see something as follows:

VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_22_57_54

Congratulations, you’ve successfully installed Arch Linux on your computer. All that is left to do now is configuring the system.

How To Configure Arch Linux

Installing Arch Linux wasn’t that hard right? In fact in my opinion, installing it is way more straightforward than configuring it. There is a lot to do here. So let’s get started.

How To Generate the Fstab File

According to the ArchWiki,

The fstab file can be used to define how disk partitions, various other block devices, or remote file systems should be mounted into the file system.

In other distributions like Ubuntu or Fedora this gets generated automatically during the installation. On Arch however, you’ll have to do it manually. To do so, execute the following command:

genfstab -U /mnt >> /mnt/etc/fstab

The genfstab program can detect all the current mounts below a given mount point and print them in fstab-compatible format to standard output. So genfstab -U /mnt will output all current mounts under the /mnt mount point. We can save that output to the /mnt/etc/fstab file using the >> operator.

How To Login to The Newly Installed System Using Arch-Chroot

Right now you’re logged into the live environment and and not into your newly installed system.

To continue configuring your newly installed system, you’ll have to first log into it. To do so, execute the following command:

arch-chroot /mnt

The arch-chroot bash script is part of the arch-install-scripts package and lets you change to the newly installed system’s root user without any reboot. How cool is that!

How To Configure the Time Zone

Once you’ve switched root, the first thing to configure is the time zone. To see a list of all the available zones, execute the following command:

ls /usr/share/zoneinfo

All the major zones should be in the directory.

VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_23_45_19

I live in Dhaka, Bangladesh which resides inside the Asia zone. If I list out the content of Asia, I should see Dhaka there:

VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_23_45_44

To set Asia/Dhaka as my default time zone, I’ll have to make a symbolic link of the file at the /etc/localtime location:

ln -sf /usr/share/zoneinfo/Asia/Dhaka /etc/localtime

The ln command is used for creating symbolic links. The -sf options indicate soft and force, respectively.

How To Configure the Localization

Now you’ll have to configure your languages. Arch Linux has an easy way to set that up as well.

First, you’ll have to edit the etc/locale.gen file according to your localization. Open the file in the nano text editor:

nano /etc/locale.gen

You’ll see a long list of languages:

VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_23_46_29

You’ll have to uncomment the languages that you want to enable. I usually only need English and Bengali. So I’ll locate the en_US.UTF-8 UTF-8, bn_BD UTF-8, and bn_IN UTF-8 languages. Save the file by pressing Ctrl + O and exit nano by pressing the Ctrl + X key combination.

Now you’ll have to execute the following command:

locale-gen

The locale-gen command will read your /etc/locale.gen file and generate the locales accordingly.

VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_23_57_55

Now that you’ve enabled multiple languages, you’ll have to tell Arch Linux which one to use by default. To do so, open the /etc/locale.conf file and add the following line to it:

LANG=en_US.UTF-8

That’s all you gotta do to configure your locale. You can always go back to the /etc/locale.gen file and add or remove languages from it. Just remember to run locale-gen whenever you do that.

Apart from the locales, if you’ve made any changes to your console keymaps in the first step of installation, you may want to persist them now. To do so, open the /etc/vconsole.conf file and add your preferred keymaps there.

For example, if you changed the default keymaps to mac-us in the first step, then you may want to add the following line to the vconsole.conf file:

KEYMAP=mac-us

Now every time you use the virtual console, it’ll have the correct keymap and you will not have to configure it every time.

How To Configure the Network

Configuring a network manually in any Linux distribution can be tricky. That’s why I advised you to install the networkmanager package during the system installation. If you did as I said, you’re good to go. Otherwise, use pacman to install the package now:

pacman -S networkmanager

Pacman is a package manager. You’ll learn more about it later. Let’s set the host name for your computer now. A host name is a unique name created to identify a machine on a network, written in the /etc/hostname file.

Open the file with nano and write your host name in it. You can use anything to identify your machine. I usually use my device brand or model as my hostname and as I’m on a legion laptop, I’ll simply write the following:

legion

Local host name resolution is provided by nss-myhostname (an NSS module provided by systemd) without having to edit /etc/hosts file. It is enabled by default.

But some software may still read the /etc/hosts file directly. Open the file in nano and add the following lines to it:

127.0.0.1        localhost
::1              localhost
127.0.1.1        legion

Make sure to replace legion with your host name. Now you may install the aforementioned package:

pacman -S networkmanager

Enable the NetworkManager service by executing the following command:

systemctl enable NetworkManager

Make sure to write NetworkManager and not networkmanager as the service name. If the command succeeds, network manager will start automatically on boot from now on and do its thing.

How To Set the Root Password

You may want to set a password for the root user because why not? To do so, execute the following command:

passwd

The passwd command lets you change the password for a user. By default it affects the current user’s password which is the root right now.

It’ll ask for a new password and confirmation password. Input them carefully and make sure you don’t forget the password.

How To Create a Non-root User

Using your Linux system as the root user for long is not a good idea. So creating a non-root user is important. To create a new user, execute the following command:

useradd -m -G wheel farhan

The useradd command lets you create a new user. Make sure to replace my name with the one you want to use. The -m option indicates that you also want it to create the corresponding home directory. The -G option will add the new user to the wheel group which is the administration user group in Arch Linux.

Now you can use the passwd command once again to set the password for the newly created user:

passwd farhan

The program will prompt you for a new password and a password confirmation. Again, don’t forget to replace my name with the one you’ve used.

Finally, you’ll have to enable sudo privilege for this new user. To do so, open the /etc/sudoers file using nano. Once open, locate the following line and uncomment it:

# %wheel ALL=(ALL) ALL

This file essentially means that all users in the wheel group can use sudo by providing their password. Save the file by hitting Ctrl + O and exit nano by hitting Ctrl + X. Now the new user will be able to use sudo when necessary.

How To Install Microcode

According to PCMag,

A set of elementary instructions in a complex instruction set computer (CISC). The microcode resides in a separate high-speed memory and functions as a translation layer between the machine instructions and the circuit level of the computer. Microcode enables the computer designer to create machine instructions without having to design electronic circuits.

Processor manufacturers such as Intel and AMD often release stability and security updates to the processor. These updates are crucial for the system’s stability.

In Arch Linux, microcode updates are available through official packages that every user should install on their systems.

# for amd processors
pacman -S amd-ucode

# for intel processors
pacman -S intel-ucode

Just installing these packages is not enough though. You’ll have to make sure that your bootloader is loading them. You’ll learn about it in the next section.

How To Install and Configure a Boot Loader

According to Wikipedia,

A bootloader, also spelled as boot loader or called boot manager and bootstrap loader, is a computer program that is responsible for booting a computer.

The internals of bootloader is out of scope of this article so I’ll just go on with the installation process. If you’ve used any other Linux distribution in the past you may have encountered the GRUB menu.

GRUB is one of the most popular bootloaders out there. Although there are a number of options available, I’ll demonstrate the installation of GRUB because it is what most people will likely use.

To install GRUB, you’ll have to first install two packages.

pacman -S grub efibootmgr

If you’re installing alongside other operating systems, you’ll also need the os-prober package:

pacman -S os-prober

This program will search for already installed operating systems on your system and will make them a part of the GRUB configuration file.

Now, you’ll have to mount the EFI system partition you created a few sections ago. To do so, you’ll have to first create an efi directory:

mkdir /boot/efi

According to Wikipedia,

In Linux, and other Unix-like operating systems, the /boot/ directory holds files used in booting the operating system.

This directory is present in all Unix-like operating systems. The above mentioned command creates a directory called efi inside the /boot directory. After creating the directory, you’ll have to mount your EFI system partition in that directory.

mount /dev/sda1 /boot/efi

I hope you remember that we formatted the /dev/sda1 device as the EFI system partition during the partitioning phase. Make sure to use the correct one for your device.

Now, we’ll use the grub-install command to install GRUB in the newly mounted EFI system partition:

grub-install --target=x86_64-efi --bootloader-id=grub

You can more or less use this command verbatim. You can change the --bootloader-id to something more expressive like arch or something else. If the installation finishes without any errors, you’ll then have to generate the GRUB configuration file.

VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_18_34_01

If you’re installing alongside other operating systems, you’ll have to enable os-prober before generating the configuration file. To do so, open the /etc/default/grub file in nano text editor. Locate the following line and uncomment it:

#GRUB_DISABLE_OS_PROBER=false

This should be the last line in the aforementioned file so just scroll to the bottom and uncomment it.

VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_18_31_41

Now execute the following command to generate the configuration file:

grub-mkconfig -o /boot/grub/grub.cfg

The grub-mkconfig command generates the GRUB configuration file and saves it to a given target location. In this case /boot/grub/grub.cfg is the target location.

The command will also take into account the microcode you installed earlier and any other existing operating system on your machine.

VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_18_35_45

Congratulations, you now have a working Arch Linux installation. At this point, you can exit the Arch-Chroot environment, unmount the partition, and reboot. But I would suggest you to stay a bit longer and set-up the graphical user interface as well.

How To Install Xorg

To run programs with graphical user interfaces on your system, you’ll have to install an X Window System implementation. The most common one is Xorg.

To install Xorg, execute the following command:

pacman -S xorg-server

Wait until the installation is done and then move on to installing the necessary graphics drivers.

How To Install Graphics Drivers

Installing graphics drivers on Arch Linux is very straightforward. You just install the packages required by your graphics processing unit and call it a day.

# for nvidia graphics processing unit
pacman -S nvidia nvidia-utils

# for amd discreet and integrated graphics processing unit
pacman -S xf86-video-amdgpu

# for intel integrated graphics processing unit
pacman -S xf86-video-intel

If you need further assistance, feel free to check the ArchWiki page.

How To Install a Desktop Environment

Now that you’ve installed Xorg and the necessary graphics drivers, you’re ready to install a desktop environment like GNOME, Plasma, or XFCE.

Arch Linux supports a long list of desktop environments but I’ve only tried out GNOME and Plasma. I’ll demonstrate how you can install either of these two.

How To Install GNOME

To install GNOME, you’ll have to install the gnome package. To do so, execute the following command:

pacman -S gnome

During the installation, you’ll be offered multiple choices for pipwire-session-manager and emoji-font packages. Accept the defaults by hitting Enter in both prompts. The installation may take some time to finish.

The gnome package comes with GDM or Gnome Display Manager. You can enable the service by executing the following command:

systemctl enable gdm

That’s all you need to do to get GNOME up and running on your Arch system.

How To Install Plasma

The KDE Plasma installation is not that different from GNOME. You’ll need to install Plasma related packages instead of GNOME.

pacman -S plasma plasma-wayland-session

If you have an NVIDIA graphics card, then avoid installing the plasma-wayland-session and use plain old X11. I own two devices with NVIDIA GPUs and both of them have shown instability when using Wayland.

During the installation, you’ll get multiple choices for ttf-font, pipwire-session-manager, and phonon-qt5-backend packages. Make sure to pick noto-fonts as your ttf-font and accept the defaults for the other two.

Like gdm in GNOME, Plasma comes with sddm as the default display manager. Execute the following command to enable the service:

systemctl enable sddm

And that’s all you need to do to get Plasma up and running on your Arch Linux system.

How To Finalize The Installation

Now that you’ve installed Arch Linux and gone through all necessary configuration steps, you can reboot to your newly installed system. To do so, first come out of the Arch-Chroot environment:

exit

Next, unmount the root partition to make sure there are no pending operations:

umount -R /mnt

Now reboot the machine:

reboot

Wait until you see the GRUB menu.

VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_20_10_25

Choose Arch Linux from the list and wait until the system finishes booting up.

VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_20_11_15

Log in with your user credentials and voilà!

VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_20_15_41

Your shiny new Arch Linux system is ready to do wonders.

How To Switch Between Desktop Environments

Unlike other distributions coupled tightly with their default desktop environment, Arch is flexible. You can switch to another desktop environment whenever you feel like it.

To do so, first logout of your current session.

VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_20_11_15

As you can see, I’m currently using Plasma. Now switch to TTY2 press Ctrl + Alt + F2 key combination. You’ll see a console login prompt:

VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_20_18_54

Login with the root credentials and disable the sddm display manager.

systemctl disable sddm

Then uninstall the Plasma related packages you installed earlier:

sudo pacman -Rns plasma plasma-wayland-session

Once the packages have been uninstalled, install the packages needed for GNOME:

pacman -S gnome

Then perform the installation according to the section you read earlier. After the gnome package has been installed, enable the gdm display manager:

systemctl enable gdm

Restart the computer.

reboot

Wait until the Arch Linux system finishes booting.

VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_20_24_11

Lo and behold, the gorgeous Gnome Display Manager. Login with your credentials.

VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_19_53_31

You can switch between the desktop environments as much as you want to, but I would suggest on settling down with one of them. Also, I wouldn’t recommend having multiples of them installed at the same time.

How To Manage Packages Using Pacman

You’ve already installed a number of packages using pacman. It’s equivalent to package managers like apt in Ubuntu and dnf in Fedora.

In this section, I’ll introduce you to some of the common pacman commands that you may need on a daily basis.

How To Install Packages Using Pacman

To install a package using pacman, you can use the following command syntax:

# sudo pacman -S <package name>

sudo pacman -S rust

You can install multiple packages as follows:

# sudo pacman -S <package name> <package name>

sudo pacman -S rust golang

You can also specify the repository you want to install the package from like this:

# sudo pacman -S <package repository>/<package name>

sudo pacman -S extra/rust

In this command, the -S option means synchronize which is equivalent to install in the case of apt or dnf package managers.

How To Remove Packages Using Pacman

To remove a package using pacman you can use the following syntax:

# sudo pacman -R <package name>

sudo pacman -R rust

This will remove the package but will leave the dependencies. You can remove the package with dependencies if they’re not required by any other package by executing the following command:

# sudo pacman -Rs <package name>

sudo pacman -Rs rust

Pacman often saves important configuration files when removing certain applications. You can override this behavior by using the following syntax:

# sudo pacman -Rn <package name>

sudo pacman -Rn rust

I usually use sudo pacman -Rns whenever I want to uninstall something. One last thing that I want to show is how to remove orphan packages.

In Ubuntu the sudo apt autoremove command uninstalls any unnecessary package. The equivalent command in Arch is:

sudo pacman -Qdtq | pacman -Rs -

This will cleanup any leftover package from previously installed packages.

How To Upgrade Packages Using Pacman

To upgrade all the packages in your system, you can use the following syntax:

sudo pacman -Syu

In this command, the S option synchronizes the packages, y refreshes the local package cache, and u updates the system. This is like the ultimate upgrade command and I run it at least once everyday.

How To Search for Packages Using Pacman

To search for a package in the database, you can use the following syntax:

# sudo pacman -Ss <package name>

sudo pacman -Ss rust

This will print out all the packages found in the database with that search term and will also indicate if any of those are already installed.

If you would like to check if a package is already installed or not, you can use the following command:

# sudo pacman -Qs <package name>

sudo pacman -Qs rust

This is useful when you want to uninstall a package but do not know its exact name.

How To Use AUR in Arch Linux

According to It’s FOSS,

AUR stands for Arch User Repository. It is a community-driven repository for Arch-based Linux distributions users. It contains package descriptions named PKGBUILDs that allow you to compile a package from source with makepkg and then install it via pacman (package manager in Arch Linux).

AUR is one of the most attractive features of Arch Linux. It’s due to AUR that Arch Linux has a package count almost equal to Debian. You’ve already used pacman to install various packages. Sadly, you can not use that to install packages from AUR.

You’ll have to install one of the AUR helpers instead. Arch Linux doesn’t support any of these helpers and advises you to learn how to build packages manually. I’ll explain both techniques here. If you understand how a helper works, you’ll be able to do it manually as well.

How To Install Packages Using a Helper

Among the available and currently maintained AUR helpers, I like the yay or yet another yogurt package. It’s written in Go and is quite solid.

You can not install yay like other packages. You’ll have to get the source code and compile the program. You’ll need git and the base-devel package to do so. Assuming you’ve already installed base-devel during Arch Linux installation:

pacman -S git

Clone the yay repository from GitHub and cd into it:

git clone https://aur.archlinux.org/yay.git && cd yay

To build and install yay from source, execute the following command:

makepkg -si

The makepkg script automates the build process of packages. The -si options stand for sync dependencies and install. The first option will install required dependencies (Golang in this case) and the later option will install the built package.

After the build process finishes, makepkg will ask for installation confirmation and your password. Input your password carefully and let the installation finish.

Check if yay has been installed properly or not:

yay --version

# yay v11.1.0 - libalpm v13.0.1

Now let’s install something using yay. One of the common packages you may want to install is the visual-studio-code-bin package. To do so, execute the following command:

yay -S visual-studio-code-bin

Unlike pacman, you shouldn’t run yay with sudo. Yay will look for the given package and will ask whether you would like to see the diff or not:

VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_21_07_26

All the repositories over at AUR comes with a PKGBUILD file which contains the instructions for building this package. Yay has this nice feature where it shows you what has changed in the PKGBUILD file since the last time.

For now, I’ll pick N for none and hit enter. Yay will now look for the dependencies and ask for your password to install them.

VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_21_19_58

Confirm the installation and provide your password. Yay will then install the dependencies and start building the package. Once built, yay will install the package and prompt for your password where necessary.

After the installation finishes, search for Visual Studio Code in the application launcher:

VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_21_28_42

Congratulations on installing your first package from AUR. Yay commands are almost identical to pacman, so if you can do something with pacman, you should be able to do that with yay as well.

In fact, yay can also install packages from official Arch Linux repositories like pacman. But I would suggest you to use yay only for installing packages from AUR when necessary and pacman for everything else.

How To Install Packages Manually

Like I said in the previous section, the ArchWiki suggests avoiding any AUR helper and installing packages from AUR manually. I’ll now show you how to do it.

Make sure you have git and base-devel packages installed. If not, use pacman to install them.

For the demonstration, let’s install Spotify this time. First visit the AUR page for the spotify package — https://aur.archlinux.org/packages/spotify/ and copy the «Git Clone URL» from there.

image-68

The page even lists all the dependencies you’ll need. Clone the repository to your machine:

VirtualBox_archlinux-2022.01.01-x86_64_16_01_2022_21_16_43

Every AUR repository comes with a PKGBUILD file containing the instructions for building the package. Whenever you’re installing a package from AUR, it’s a great idea to checkout the PKGBUILD file using something like the cat command:

VirtualBox_archlinux-2022.01.01-x86_64_16_01_2022_21_22_37

Make sure there’s nothing harmful in the file. Once you’re satisfied, use makepkg to install any dependencies, build the package, and install it. Ideally there shouldn’t be any issues but sometimes, things can take an unexpected turn.

VirtualBox_archlinux-2022.01.01-x86_64_16_01_2022_21_34_29

In these cases, go back to the corresponding AUR page and check the user comments. Like in this case, I found the following pinned comment:

image-69

Turns out the package requires you to add the Spotify for Linux gpg key to the user kyechain. This command downloads the gpg key using curl and pipes it as the input of the gpg --import command:

VirtualBox_archlinux-2022.01.01-x86_64_16_01_2022_21_37_50

Try executing makepkg -si once again and everything should work fine this time:

VirtualBox_archlinux-2022.01.01-x86_64_16_01_2022_21_39_33

See, told ya! Manually installing packages often involves such troubleshooting but help is almost always around the comment corner. Let’s enjoy some music now.

How To Troubleshoot Common Problems

Look, I’ve been using Arch as my primary on all my devices for some years now but I still run into issues. Fortunately there are some great places to look for help when you’re stuck:

  • ArchWiki
  • Arch Linux Forum
  • r/archlinux

For the most part, the wiki should have the information you’re looking for. In fact, if you’re on a laptop and having difficulty getting something to work, there is an entire wiki category dedicated to different laptops. So look around the wiki.

If the wiki fails to solve your problem, then ask other fellow users at the forum as well as the subreddit. But whenever you’re doing that, make sure to do your research first and include as much description as you can in the post. It’s really annoying if other users have to keep asking you for more information and it’ll also lower the chance that you’ll get an answer.

Whatever people may say, Arch Linux is very stable as long as you know what you’re doing. If you go about installing every funky package you come across in the AUR or keep switching different kernels without knowing what they’re for, your system may fail to boot.

In those cases, you can use your live USB drive as a rescue media. To do so, reconnect the bootable USB to your computer and boot into the live environment. Once there, configure the time, keymaps, and fonts if you want to.

Then use fdisk to list out all your partitions and locate the one holding your Arch Linux installation. In my case it’s the /dev/sda2 partition. Mount the partition like you did before:

mount /dev/sda2 /mnt

Now use Arch-Chroot to log in as the root user.

arch-chroot /mnt

Now uninstall the bad package you installed or go back to a kernel version that used to work in the past and so on. Once done, exit the Arch-Chroot environment, unmount the partition, and reboot:

exit
umount -R /mnt
reboot

If the computer boots fine then congratulations. Otherwise try the wiki, forum, or the subreddit. If nothing works, you may have to do a fresh install.

Further Reading

If you’ve come this far then you’ve done a lot of reading already – but that’s not all. This entire handbook was written by combining information from the wiki, forum, and subreddit. I’m listing out some wiki pages that I think you should read.

  • Installation guide
  • Network configuration
  • General recommendation
  • Desktop environment
  • pacman
  • Arch Build System
  • makepkg
  • List of applications

Couldn’t think of any more at the moment but I’ll keep this list updated.

Conclusion

I would like to thank you from the bottom of my heart for the time you’ve spent on reading this article. I hope you’ve enjoyed your time and have learned a lot about not only Arch but Linux in general

Apart from this one, I’ve written full-length handbooks on other complicated topics available for free on freeCodeCamp.

These handbooks are part of my mission to simplify hard to understand technologies for everyone. Each of these handbooks takes a lot of time and effort to write.

If you’ve enjoyed my writing and want to keep me motivated, consider leaving starts on GitHub and endorse me for relevant skills on LinkedIn.

I’m always open to suggestions and discussions on Twitter or LinkedIn. Hit me with direct messages.

In the end, consider sharing the resources with others, because

In open source, we feel strongly that to really do something well, you have to get a lot of people involved. — Linus Torvalds

Till the next one, stay safe and keep learning.

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Для работы проектов iXBT.com нужны файлы cookie и сервисы аналитики.
Продолжая посещать сайты проектов вы соглашаетесь с нашей
Политикой в отношении файлов cookie

В современной Linux-тусовке бытует мнение, будто установка Archlinux — это весьма сложный и утомительный процесс, а неподготовленному пользователю даже не стоит и пытаться лесть в эти дебри. В этом материале мы попытаемся наглядно опровергнуть все эти глупые заблуждения на примере нового установщика Archlinux.

Содержание

  • Подготовка
  • Установка
  • Файлы
  • Пользователь
  • Компоненты системы
  • Пример рабочей системы
  • Итоги
  • Видеоверсия

Подготовка

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

Скачать чистую систему без лишних пакетов и вирусов вы всегда можете с официального сайта проекта. Запись же на носитель лучше производить с помощью Belena Etcher во избежание ошибок. Перейдём к установке.

Установка

Установка весьма проста и не должна вызвать каких-либо затруднений. Вставляем наш носитель в PC и перезагружаемся. Встречает нас командная строка. Вводим команду ArchInstall и дожидаемся срабатывания скрипта.

Скрипт запускает меню конфигурации, в котором по порядку указаны варианты настройки модулей системы. Пропускаем первые два пункта, отвечающих за язык установщика c вводом, и переходим к конфигурированию будущей ОС. Чтобы не плодить сотни скриншотов, поделим установку на модули: файлы, пользователь и компоненты системы.

Файлы

Select mirror region
Select harddrives
Select disk layout
Выбор файловой системы
Set encryption password
Select boot loader
Use swap
Specify hostname
  • Select mirror region отвечает с репозиториев какой страны вы будете скачивать пакеты для работы и установки OC. 
    Выбираем свою страну и продолжаем.
  • Select harddrives позволяет указать, на какой диск установить систему. Вновь выбираем желаемый носитель.
  • Select disk layout отвечает за форматирование. Выбираем Wipe all (удалить всё с диска) и желаемую файловую систему.

Файловые системы:

  1. BTRFS — новая файловая сочитающая в себе сохранность данных и скоротные показатели. Использовать только для SSD.
  2. EXT4 — проверенная временем универсальная файловая система, что идеально подходит HDD и SSD.
  3. F2FS — файловая система созданная специально дря раскрытия потенциала SSD-носителей от компании Samsung.
  4. XFS — старая файловая система для киношных станций. Для десктопа не подходит.
  • Set encryption password можно пропустить, если вам не нужно шифрование содержимого на диске. Лично я пропускаю.
  • Select boot loader отвечает за выбор загрузчика, тоесть того ПО, которое будет грузить нашу систему.
    На самом деле загрузчиков весьма много, но разработчики ArchLinux выбрали из коробки не самый лучший выриант.
    Выбираем yes, и загрузчик сам изменится на привычный Grub.
  • Следующие два пункта посвящены созданию Swap и именованию компьютера в сети (Use swap и Specify hostname), их можно пропустить, так как никакого существенного влияния на работу будущей системы это не окажет.

Пользователь

Set root password
Specify user account

Наконец-то мы подобрались к основным модулям, что отвечают за добавление и настройку аккаунта пользователя:
Set root password (Назначить пароль администратора), Specify user account (создать отдельного пользователя). Вновь вводим желаемые данные и переходим к конфигурированию основных компонентов системы.

Компоненты системы

Specify profile
Выбор рабочего окружения
Выбор видеодрайвера

Specify profile позволяет выбрать весьба обширный список заранее подготовленных компонентов: предварительную пакетную базу, графическое окружение (DE) и видеодрайверы. Если вы не являетесь прошаренным пользователем, то выбирайте Desktop, KDE или Gnome и видеодрайвер в зависимости от вашей видеокарты. Следом уже пойдут пункты отвечающие за звук (Select audio), ядро системы (Select kernels), добавление ПО (Packages to install), настройка времени (Select timezone и Set automatic time sync).
Всех их можно пропустить, так как они уже заранее настроены. (Если не используете DE, то укажите Select audio).

Configure Network
Repositories to enable

Выбираем теперь настройку интернета (Configure Network) и задействуем репозиторий с 32-битными библиотеками (Repositories to enable). Для любого типа подключения лучше использовать NetworkManager из-за своей универсальности и multilib, если собираетесь устанавливать Wine или Steam. Выбираем Install и начинаем установку. 

Видеоверсия установки

Пример рабочей системы

Если вы всё сделали правильно и выбрали Gnome как рабочее окружение, то вы получите примерно такую систему.
Всю дополнительную информацию о послеустановочной настройке вы всегда можете найти в теме оптимизации ArchLinux или в нашем файле ARU.

Итоги

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

Видеоверсия

Сейчас на главной

Новости

Публикации

Процесс обрезки, кронирования деревьев,
расчистка зарослей порой занимает много времени и сил. Сегодня у меня обзор
компактной аккумуляторной цепной пилы Violeworks с длиной
направляющей шины 6…

Machenike K520 — это полноформатная механическая клавиатура с мультипрофильным игровым режимом, цветной подсветкой и поддержкой макросов. Содержание Параметры Конфигурации…

Еще недавно компания Beelink выпустила свой новый компактный компьютер SER6 Pro на процессоре AMD Ryzen 7 7735HS, как поспешила выпустить обновление, логичное настолько, что следовало бы сделать…

Несмотря на то, что этот контроллер на рынке уже давно,
а в последнее время всё чаще и чаще встречается его наследник с поддержкой PCIe Gen4, мне с ним познакомиться всё никак не удавлюсь до конца…

ELTRONIC
20-61 FIRE BOX 1000 можно назвать одной из самых привлекательных новинок бренда
ELTRONIC, потому что она яркая, мощная и пробивная. Появившись в начале весны
2023 года, она стала очень…

Современные смартфоны предоставляют возможность пользоваться удобными
приложениями навигации, которые помогают нам быстро и легко ориентироваться в
незнакомых местах. Однако многие из нас не…

Arch Linux is a general-purpose rolling release Linux distribution that is very popular among DIY enthusiasts and hardcore Linux users.

The default installation covers only a minimal base system and expects the end-user to configure the system by himself/herself.

This is why installing Arch Linux is a challenge in itself but at the same time, it is a learning opportunity for intermediate Linux users.

Fret not, you can easily get Arch Linux up and running if you follow the steps mentioned below.

How to install Arch Linux

How to install Arch Linux

As of now, there are two ways using which you can install Arch Linux:

  • Without the guided installer
  • With the help of Archinstaller (guided installer)

In case you didn’t know, Arch Linux introduced a guided installer in 2021 (a menu based system to help you easily configure things for installation).

In this tutorial, we focus on configuring things ourselves, without the need of archinstaller. It is potentially more time-consuming, and if you are new to Arch Linux, you might want to refer to our separate tutorial, where we use the guided installer to install Arch Linux using VirtualBox.

Beginner’s Guide to Installing Arch Linux on VirtualBox

Arch Linux is hugely popular in the desktop Linux world. One of the reasons for its popularity is that installing Arch Linux itself is a complicated task. I am not exaggerating. Installing Ubuntu or Debian is a lot easier task than Arch Linux because they have GUI based installers. Arch

It’s FOSSAnkush Das

The installation steps can differ at some points depending on whether you have a UEFI or legacy BIOS system. Most new systems come with UEFI these days.

I have written it here with a focus on the UEFI system but I’ll also mention the steps that are different for the legacy BIOS systems.

🚧

The method discussed here wipes out existing operating system(s) from your computer and installs Arch Linux on it. So if you are going to follow this tutorial, make sure that you have backed up your files, or else you’ll lose all of them. You have been warned.

But before you see how to install Arch Linux from a USB, please make sure that you have the following requirements:

Requirements for installing Arch Linux:

  • An x86_64 (i.e. 64 bit) compatible machine
  • Minimum 512 MB of RAM (recommended 2 GB)
  • At least 2 GB of free disk space (recommended 20 GB for basic usage with a desktop environment)
  • An active internet connection
  • A USB drive with a minimum 2 GB of storage capacity
  • Familiarity with the Linux command line

Once you have made sure you have all the requirements, let’s install Arch Linux.

Step 1: Download the Arch Linux ISO

You can download the ISO from the official website. Both direct download and torrent links are available.

Step 2: Create a live USB of Arch Linux

You will have to create a live USB of Arch Linux from the ISO you just downloaded.

You may use the Etcher GUI tool to create the live USB. It is available for both Windows and Linux.

Arch Linux Live Usb

Using Etcher to create Arch Linux live USB

Alternatively, if you are on Linux, you can use the dd command to create a live USB. Replace /path/to/archlinux.iso with the path where you have downloaded the ISO file, and /dev/sdx with your USB drive in the example below. You can get your drive information using lsblk command.

dd bs=4M if=/path/to/archlinux.iso of=/dev/sdx status=progress && sync

Stick to balenaEtcher if you are comfortable with a GUI.

Step 3: Boot from the live USB

Do note that in some cases, you may not be able to boot from live USB with secure boot enabled. If that’s the case with you, disable the secure boot first.

Once you have created a live USB for Arch Linux, shut down your PC. Plugin your USB and boot your system. While booting keep pressing F2, F10 or F12 key (depending upon your system) to go into boot settings.

Here, select to boot from USB or removable disk. Once you do that and the system boots, you should see an option like this:

arch linux boot screen

Arch Linux Boot Screen

Select Boot Arch Linux (x86_64). After various checks, Arch Linux will boot to the login prompt with the root user.

Not using US keyboard? Read this

The default keyboard layout in the live session is US. While most English language keyboards will work just fine, the same cannot be true for French, German and other keyboards.

If you face difficulty, you can list out all the supported keyboard layout:

ls /usr/share/kbd/keymaps/**/*.map.gz

And then change the layout to the an appropriate one using loadkeys command. For example, if you want a German keyboard, this is what you’ll use:

loadkeys de-latin1

The next steps include partitioning the disk, creating the filesystem and mounting it.

📋

Again, read all the instructions properly and follow each step carefully. You miss one step or ignore something and you’ll have difficulty installing Arch.

Step 4: Partition the disks

For partitioning the disks, we’ll use command line based partition manager fdisk.

Use this command to list all the disk and partitions on your system:

fdisk -l

📋

Your hard disk should be labelled /dev/sda or /dev/nvme0n1. Please use the appropriate disk labeling for your system. I am using /dev/sda because that’s more common.

First, select the disk you are going to format and partition:

fdisk /dev/sda

I suggest that you delete any existing partitions on the disk using command d. Once you have the entire disk space free, it’s time to create new partitions with command n.

Check if you have UEFI mode enabled

Some steps are different for UEFI and non-UEFI systems.You should verify if you have UEFI enabled system or not. Use this command:

ls /sys/firmware/efi/efivars

If this directory exists, you have a UEFI enabled system. You should follow the steps for UEFI system. The steps that differ are clearly mentioned.

Create an ESP partition (For UEFI systems only)

If you have a UEFI system, you must create an EFI partition at the beginning of your disk. Otherwise, skip this step.

When you enter n, it will ask you to choose a disk number, enter 1. Stay with the default block size, when it asks for the partition size, enter +512M.

fdisk new efi

Creating EFI System Partition

One important steps is to change the type of the EFI partition to EFI System (instead of Linux system).

Enter t to change type. Enter L to see all the partition types available and then enter its corresponding number to the EFI system.

change type of efi system partition

Change Type of EFI System Partition

Create root partition

You need to create root partition for both UEFI and legacy systems.

The common partitioning practice was/is to create root, swap and home partitions separately. You may just create a single root partition and create a swapfile and home under the root directory itself.

So, in this approach, we’ll have a single root partition, no swap, no home.

While you are in the fdisk command, press n to create a new partition. It will automatically give it partition number 2. This time keep on pressing enter to allocate entire remaining disk space to the root partition.

new partition

New Partition

When you are done with the disk partitioning, enter w command to write the changes to the disk and exit out of fdisk command.

Step 4: Create filesystem

Now that you have your disk partitions ready, it’s time to create filesystem on it. Follow the steps for your system

Creating filesystem for UEFI system

So, you have two disk partitions and the first one is EFI type. Create a FAT32 file system on it using the mkfs command:

mkfs.fat -F32 /dev/sda1

Now create an Ext4 filesystem on the root partition:

mkfs.ext4 /dev/sda2

Creating filesystem for non-UEFI system

For non-UEFI system, you only have one single root partition. So just make it ext4:

mkfs.ext4 /dev/sda1

Step 5: Connect to WiFi

You can connect to WiFi interactively using this helpful utility called iwctl. Just enter this command and follow the on-screen instructions:

iwctl

Next, you can list all your wireless interfaces/devices connected using the command:

device list

You need to select the preferred one.

Once you select the wireless interface, scan for available network using the command below:

station wlan0 scan

While it scans for the network, you don’t get to see the network names yet. So, to see the connections available, you can type in:

station wlan0 get-networks

Among the listed networks, you can connect to your target Wi-Fi using the command:

station wlan0 connect "Name of Network/WiFi"

If it is protected by a password, you will be asked for it, enter the credentials and you should be connected to it.

Exit the network setup prompt using Ctrl + D.

Now, we’re connected to the network, but to make sure, you can check if you could use the internet by using the ping command:

ping google.com

If you get bytes in reply, you are connected. Use Ctrl+C to stop the ping reply.

Step 6: Select an appropriate mirror

This is a big problem with installing Arch Linux. If you just go on installing it, you might find that the downloads are way too slow. In some cases, it’s so slow that the download fails.

It’s because the mirrorlist (located in /etc/pacman.d/mirrorlist) has a huge number of mirrors but not in a good order. The top mirror is chosen automatically and it may not always be a good choice.

Thankfully, there is a fix for that. First sync the pacman repository so that you can download and install software:

pacman -Syy

Now, install reflector too that you can use to list the fresh and fast mirrors located in your country:

pacman -S reflector

Make a backup of mirror list (just in case):

cp /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.bak

Now, get the good mirror list with reflector and save it to mirrorlist. You can change the country from US to your own country.

reflector -c "US" -f 12 -l 10 -n 12 --save /etc/pacman.d/mirrorlist

All good to go now.

Step 7: Install Arch Linux

Since you have all the things ready, it’s time to finally install the Arch Linux. You’ll be installing it on the root directory so mount it first.

Do you remember the name of the root partition? Use it to mount it:

mount /dev/sda2 /mnt

Note that this is valid for UEFI systems, you will have to use /dev/sda1 in non-UEFI systems.

With root mounted, it’s time to use the wonderful pacstrap script to install all the necessary packages:

pacstrap /mnt base linux linux-firmware vim nano

It will take some time to download and install these packages. If the downloads get interrupted, no need to panic. You can run the above command once again and it resumed the download.

I have added Vim and Nano text editor to the list because you’ll need to edit some files post-installation. You can use anything you are comfortable with.

For reference, head to our nano vs vim article to explore the differences between these editors.

Step 8: Configure the installed Arch system

Generate a fstab file to define how disk partitions, block devices, or remote file systems are mounted into the filesystem.

genfstab -U /mnt >> /mnt/etc/fstab

Now use arch-chroot and enter the mounted disk as root. Actually, now you are using the just installed Arch Linux system on the disk. You’ll have to do some configuration changes to the installed system so that you could run it properly when you boot from the disk.

arch-chroot /mnt

Setting Timezone

To set up timezone on Linux, you can use timedatectl command. First find your time zone:

timedatectl list-timezones

Exit from the list using Ctrl + C or just q. And then set it up like this (replace Europe/Paris with your desired time zone):

timedatectl set-timezone Europe/Paris

Setting up Locale

This is what sets the language, numbering, date, and currency formats for your system.

The file /etc/locale.gen contains all the local settings and system language in a commented format.

Open the file using Vim or Nano editor and uncomment (remove the # from the start of the line) the language you prefer.

The command to open the file looks like:

nano /etc/locale.gen

localegen

Locale Gen

I have used en_GB.UTF-8 (English with Great Britain). Hit Ctrl + X and then Y to save the selection and continue.

Now generate the locale config in the /etc directory file using the below commands one by one:

locale-gen
echo LANG=en_GB.UTF-8 > /etc/locale.conf
export LANG=en_GB.UTF-8

Both locale and timezone settings can be changed later on as well when you are using your Arch Linux system.

Network configuration

Create a /etc/hostname file and add the hostname entry to this file. Hostname is basically the name of your computer on the network.

In my case, I’ll set the hostname as myarch. You can choose whatever you want:

echo myarch > /etc/hostname

The next part is to create the hosts file:

touch /etc/hosts

And edit this /etc/hosts file with Vim or Nano editor to add the following lines to it (replace myarch with hostname you chose earlier):

127.0.0.1	localhost
::1		localhost
127.0.1.1	myarch

Set up root password

You should also set the password for the root account using the passwd command:

passwd

You will be prompted to enter (and re-type) your password to confirm.

Step 9: Install Grub bootloader

This is one of the crucial steps and it differs for UEFI and non-UEFI systems. Let me mention the steps for the UEFI systems first.

Make sure that you are still using arch-chroot. Install required packages:

pacman -S grub efibootmgr

Create the directory where EFI partition will be mounted:

mkdir /boot/efi

Now, mount the ESP partition you had created

mount /dev/sda1 /boot/efi

Install grub like this:

grub-install --target=x86_64-efi --bootloader-id=GRUB --efi-directory=/boot/efi

One last step:

grub-mkconfig -o /boot/grub/grub.cfg

Install grub on Non-UEFI systems

Install grub package first:

pacman -S grub

And then install grub like this (don’t put the disk number sda1, just the disk name sda):

grub-install /dev/sda

Last step:

grub-mkconfig -o /boot/grub/grub.cfg

Step 10: Create Additional user and enforce privileges

You should not boot into a system, which has only a root user account. This way, every change you make will happen without any authentication required, and you might end up messing up your system.

Of course, you can still choose to do it, but it is not the recommended solution for a stable and secure experience.

So there should be an additional user, who gets root privileges using sudo. That reminds me, you should also install the sudo package if you didn’t already:

pacman -S sudo

Now create a new user and give permissions. In my case, ‘team’ is the new username I chose. You can select your own.

useradd -m team
passwd team

Enter the password for this user and confirm. Now, you will be adding this user to a group of users that grants specific permissions. This should be self-explanatory, while the wheel group is needed for a user act as the super user.

usermod -aG wheel,audio,video,storage team

Finally, you need to edit the visudo file, specifically the line referring to wheel should be uncommented as shown in the image below.

It opens in VI editor by default. So we need to force it use nano:

EDITOR=nano visudo

visudo

Edit visudo

Save the changes and exit from this file.

Step 11: Install a desktop environment (GNOME in this case)

The first step is to install the X environment. Type the below command to install the Xorg as display server along with the network manager. You can refer to the official documentation for Wayland.

pacman -S xorg networkmanager

Now, you can install GNOME desktop environment on Arch Linux using:

pacman -S gnome

The last step includes enabling the display manager GDM for Arch. I also suggest enabling Network Manager

systemctl enable gdm.service
systemctl enable NetworkManager.service

Now exit from chroot using the exit command:

exit

Finally, unmount the root partition using the following command:

umount /mnt

Or,

umount -l /mnt

And then shut down your system

shutdown now

Don’t forget to take out the live USB before powering on the system again. If everything goes well, you should see the Grub screen and then the GNOME login screen.

If you want a KDE desktop, please follow this tutorial about installing KDE on Arch Linux.

Final Words on Arch Linux installation

You might have realized by now that installing Arch Linux is not as easy as installing Ubuntu. However, with a little patience, you can surely accomplish it and then tell the world that you use Arch Linux.

Arch Linux installation itself provides a great deal of learning. I recommend a few essential things to do after installing Arch Linux where you’ll find steps to install various other desktop environments (if you didn’t install it here) and learn more about the OS.

7 Essential Things To Do After Installing Arch Linux

Brief: This tutorial shows you a few essential things to do after installing Arch Linux. This will help you get started with Arch Linux so that you can explore it further. Earlier I showed you how to install Arch Linux. Today, I am going to list a few basic and

It’s FOSSAbhishek Prakash

You can keep playing with it and see how powerful Arch is.

Let us know in the comments if you face any difficulty while installing Arch Linux.

In this «How To Install Arch Linux» blog we will cover how to build Arch Linux, what are prerequisites for Arch Linux setup and also at the end we have answered the commonly asked questions

This operating system (OS) installation steps includes Arch Linux server download, Arch Linux install, how to make bootable pen drive, how to create a partition in Linux step by step, configuration, Arch desktop install. I also made a video for your ease of  «How To Install Arch Linux 2021 [Installation Guide] »  Click on the below video to watch the live installation.

  • What is Arch Linux
  • Arch Linux System Requirements
  • Arch Linux Download
  • How to Create Bootable Pendrive
  • UEFI vs Legacy
  • How to Boot Arch Linux
  • Install Arch Linux
  • Connectivity Checks
  • How to partition Arch Linux
  • Mounting Filesystem in Linux
  • Configure Linux
  • Generating fstab file in Linux
  • Generating and Editing Locale File In Linux
  • Configuring NTP in Linux
  • Setting Up Hardware Clock in Linux
  • Editing hostname in Linux
  • Editing Hosts file in Linux
  • Downloading and Installing GRUB in Linux
  • Configuring GRUB Bootloader in Linux
  • Installing and Enabling Network Manager in Linux
  • Installing GUI Mode in Linux
  • Commonly Asked Questions

What Is Arch Linux? 

In simple words, Arch Linux is a light weighted & flexible distribution among other existing distributions. Its main motive is to provide simplicity, truly open-source and up-to-date OS. This distribution follows a rolling release model i.e, your kernel and software will always be up to date whenever available. It provides faster updates as compared to other versions of Linux. Updating Arch is quick, just run a single command and your Arch will be updated as a new Arch you don’t require to move from one version to another. By default, Arch is installed as minimal (An installation process without GUI) which called Arch minimal installation

Arch Linux System Requirements

  • A 64 bit supported machine
  • Required at least 1 GB of RAM (Our recommendation is 2 GB of RAM)
  • At least 18 GB of free disk space ( Our recommended is 30 GB for basic usage with a GUI environment)
  • Internet connection (Fast internet will speed up installation process)
  • A USB drive with a minimum of 4 GB of storage capacity

Arch Linux Download 

You can download archiso from the official website in two ways either you can choose torrent or you can go with direct. Here is the official link to Arch Linux.

Scroll down after opening the website and choose mirrors according to your country. In the below picture, I have chosen India.

What Is Arch Linux?

How To Create Bootable Pendrive

If you are done with downloading Archiso our next step is to make a boot device. If you have a Windows platform you can easily do that by using the Rufus tool and If you are a Linux user then you can do it with a single command. Other mediums are available, like DVD and Network but they are not in much use.

dd if=<file> of=<device> bs=4M; sync; eject <device>

So here the file = the downloaded archiso file which will be in your downloads directory, the device is referring to your USB Flash drive name which will be shown like /dev/sdx, where «x» denotes your disk name depending on the system it may vary, and the rest of the command will be the same. below you can take reference of how exactly it looks like:

To know the full step-by-step process of how to make a bootable USB Flash drive with Windows and Linux you can click on How to Create Bootable USB | Linux Bootable USB | Windows Bootable USB

UEFI vs Legacy 

So, these (operating system) OS installation steps vary at some points depending upon your system, which might be UEFI or a Legacy boot system. To look over which is your type, you can easily examine. so if you are using windows then type «System Information» in the search bar and it will open an application with details of your system then you just have to navigate for «BIOS Mode«. The easiest method to find your type is UEFI or BIOS (Legacy) just look for a directory /sys/firmware/efi. The directory will be missing if your system is using BIOS. and if you can see it means you are using UEFI.

How To Boot Arch Linux?

After making a bootable device now just attach your Pendrive to the system, restart your Laptop/PC and keep pressing the F2, F10 or F12 key from your keyboard to open the boot menu which looks like the below picture. Now just select your boot device and boot Arch. In my case, it is Kingston USB.

Note: Boot options keys may vary so click on Boot Menu Option Keys For All Computers and Laptops to know which one is for your laptop or computer.

How To Boot Arch Linux

Note: You can also use the installer (zen installer) to install Arch in GUI Mode, but according to my experience it is not stable right now. Hence I recommended going with the manual installation process instead of an installer.

Install Arch Linux

Step 1: Once you boot your device from the boot menu, then the below screen will appear from which you have to select the first option “Arch Linux install medium (x86_64, BIOS)” and then hit Enter key from your keyboard.

Arch Linux Install Guide

Connectivity Checks

Step 2: Now you will see some arch boot log and system checks. So, within a few seconds, after examining, Arch will boot and logging you into a root prompt. Here we will insert the “IP link” command to test the availability of network adapters.

ip link

You can verify your output by matching it with the below picture to ensure that your command runs perfectly.

Connectivity Checks

Step 3: We will load and install the package but before that, it is good to examine your internet connection by inserting the “ping” command.

ping google.com

In the below picture, you can observe the output of a ping, where packets are coming in sequence, so it means the Internet is working. In case you get “host unreachable” then please check your internet connection or router.

Arch Linux Download 

Step 4: Now after completing connectivity checks, we can move ahead to our installation. Here we will add mirrors to our “mirrorlist” file so that our packages will download at maximum speed from the nearest server, but this step is optional you can completely skip that if you have a fast internet connection.

reflector -–verbose -c “India” --sort rate > /etc/pacman.d/mirrorlist

Here reflector is used to find the nearest mirror and the sort rate is used to sort the nearest mirror from your nearest server, you can choose the server according to your location In my case it’s India.: 

Reflector Command Demonstration

Step 5: After adding a mirror our database also requires a fresh updated mirror list. Let’s sync the Pacman repository so that you can download and install the software.

pacman -Syy

Note: In some cases, Caps lock does not work when you want to use upper case, so if this is your case then use the shift key instead of caps lock e.g., Shift + A will type capital A.

Step 6: Now we have completed all the pre-settings and checking. So, we can now begin with the installation process of our operating system. So, let’s insert “lsblk” command into a list of devices currently active with your system.

lsblk

Here our main focus is on our disk where we want to install Arch. So, In my case, its name is“sda” of 20.1GB size. Your case size might be varied, but the device label “sda” is mostly the same if you are using a fresh disk.

lsblk Command Demonstration

So from this step, you will not only get to know how to install Arch OS on your disk you will also learn how to create partitions on a disk using a command line with fdisk utility.

How To Partition Arch Linux?

Step 7: Now we will begin with partitioning our disk by using fdisk utility (It is a pre-defined command-line utility that helps to customize partitions of disks). You can also go for cfdisk if you want GUI utility. So, type fdisk and your device name next to fdisk.

fdisk /dev/sda

change “sda” with your device name (In my case the device name is «sda») and the rest of the part will be the same for you.

How To Partition Arch Linux

Step 8: Now we are in fdisk utility where we will run a few commands to create partitions. So, here we need to create two partitions one for “root” and one for “swap”.

Enter "p" to check the partition table

Enter "n" to create a new partition

In the below picture, I have first-run “p” command and got nothing, which means I have currently no partition and then I have run the “n” command to begin with a new partition. (If you are using a fresh disk you will see the same)

How To Partition Linux

Step 9: After that, it will ask you to choose partition type so we will choose primary by typing “p” again

Follow the below sequence of steps carefully.

  • Now it will ask for a partition number so we will go with default by entering “1”
  • Next, it will ask for sectors, so here just we will hit “enter” to go with the default
  • Now it will ask you for the size of the partition. So here I have chosen 18GB by entering “+18G” you can choose any size but make sure it is more than 15 GB
  • Now we have created one partition which you can examine again by typing the “p” and now you will able to see one new row. It means we have created one primary partition which we will use for root.

Creating Root Partition

Step 10: Here we will repeat our above step [8] & [9] to create one more partition for swap. Hereafter pressing “n” you can blindly press “Enter ” from your keyboard three times to create a partition with the remaining disk size. I have done the same in the below picture.

Creating Swap Partition

Step 11: Now we have also created our second partition, but to convert this partition into swap, we need to change the type of this partition from Linux to Swap. So, to do this follow the below sequence of steps:

  • Type “t” and press “Enter Key”
  • Now choose your partition number which will be 2 so just type “2” and then again hit «Enter«
  • Now it will ask you to type a value so that you can convert it into your desired type so to know the code you just have to type “l” and hit «Enter»

Changing Filesytem

Step 12: Now it will show you a list of types. So here just navigate to “82 Linux swap /Solaris” and then just type “82” and press “Enter”

Filesytem Codes

Step 13: Now we have changed our type which you can examine by typing “p”. So, we are done with partitioning, now we can save it by entering “w”. So, it will update the changes.

Saving Partition Table

Mounting Filesystem In Linux

Step 14: Now is the time to clean our newly build partitions and make them available for our use, for that first type “lsblk” again to check the device name. Now, as you can see below the picture it is showing sda1 and sda2 which we have currently created. So, I will clean the first sda1 for root. For that run “mkfs”  with “ext4” to format it into ext4 format.

mkfs -t ext4 /dev/sda1

change device name with yours if you have a different in my case it is sda1.

Mounting Filesystem In Linux

Step 15: Now after formatting root, we will format our swap device also, for that run “mkswap” command and choose your second partition, In my case, it is «sda2»

mkswap /dev/sda2 (for formatting swap)

Now we will mount the root partition to the mnt directory.

mount /dev/sda1 /mnt (For mounting root)

So let’s enable our swap partition with the below code.

swapon /dev/sda2 (for enabling swap)

Mounting Swap Filesystem

Step 16: Now we will run “lsblk” command to check our mounted filesystems. So, in the below picture, you can see that both partitions which we have mounted.

Verifying Mounted Filesystems

Now we have set up everything which is needed to install the package.

Note: So Now you have learned how to create partitions. So, like that, you can also create one more partition which you can use later for your personal files storage, but this is also optional.

Let’s install the package in our newly created partitions.

Configure Linux

Step 17: Now we will move ahead to setting up Linux. So, we will now install Arch Linux base, firmware and other important utilities with the Arch package to our root filesystem by running the below-mentioned Arch Linux install command.

pacstrap -i /mnt base linux linux-firmware sudo nano vi

After entering the command, it will ask you a few times to enter 1 and Y so just do these same to go with defaults. It will take some time to install so just wait and give default inputs when it asks.

Configure Linux

So, we are done with our installation. Now we can start configuring our system

Now you will get to know what things are required when any Linux installed. Basically, these steps are automatically performed in the backend when installing any other Linux like Ubuntu, Fedora, Mint, etc. So, let’s begin with the configuration of Arch and update our brains with this new knowledge.

Generating fstab File in Linux

Step 18: Now we need to generate «fstab» file for defining a permanently mounted system. Basically, this file is a very important file in all Linux systems whose main motive is to store information on filesystems and their mount points so, run the below-mentioned code

genfstab -U -p /mnt >> /mnt/etc/fstab

(/etc/fstab is the location or path of a file) Now After that, we will change our root prompt into our installed Linux root prompt for internal configuration with the chroot.

arch-chroot /mnt

Generating fstab File in Linux

Generating And Editing Locale File in Linux

Now we will set our language by generating and editing the locale file

Step 19. Let’s set up now our system language, date, numbering and currency by editing the locale file. So first we will create it and then we will edit it So, follow the below line code.

nano /etc/locale.gen

Generating And Editing Locale File in Linux

Step 20: Now we will edit our locale file, so navigate to your field according to your region. In my case it is India so I am choosing “en_IN UTF-8”. To allow it, just remove the “#” from that and save the file by using the shortcut key «Ctrl+o» and then exit from it by «Ctrl+x«. (Take reference from the below image for removing #).

Editing Locale File

Step 21: Now we will generate locales by running the locale-gen command.

locale-gen

Setting Language

Now we are done with the change locale step. so we will set a date and time now.

Configuring NTP in Linux

Step 22: Now we will configure the locale.conf file set the timezone and enable NTP (network time protocol) so that it can update time according to the internet. So, follow the below line codes. and remember to replace “IN” with your region which you also have set on the step [20]. (Rest of the part will be the same for you)

echo “LANG=en_IN.UTF-8” > /etc/locale.conf

Now here again select a time zone according to your location, In my case, it is Asia, Kolkata. (Rest of the part will be the same for you)

ln -sf /usr/share/zoneinfo/Asia/Kolkata /etc/localtime

Let’s set NTP so that it automatically set time with the internet, following the below-mentioned code.

timedatectl set-ntp true

Configuring NTP in Linux

Setting Up Hardware Clock in Linux

Step 23: Now let’s set the hardware clock in our system from system to hardware by following the below line code.

hwclock –systohc

 You can verify changes by running the date command.

date

Setting Up Hardware Clock In Linux

Editing Hostname in Linux

Step 24: Now we will move ahead and edit the hostname i.e., (your computer name basically) by following the below piece of code.

echo techofide > /etc/hostname

You can give a name of your own choice instead of «techofide». Now let’s create the hosts’ file to add the host.

nano /etc/hosts

Editing Hostname In Linux

Editing Host File in Linux

Step 25: Now we will add these lines inside our “hosts” file.

127.0.0.1         localhost

::1               localhost

127.0.1.1         techofide.localdomain       techofide

Give the hostname which you have previously chosen instead of «techofide». (rest of the content will be the same)

Editing Hosts File in Linux

Now save the file by using the Shortcut key «Ctrl +o» and exit from that with «Ctrl +x».

Step 26: Now let’s set a password for our root user by following the below code.

passwd

After entering it will ask password so type the password of your choice. (In Linux whenever you type any credential it will work as silent i.e, during typing it will not reflect anything on your screen as acknowledgement, so type blindly your password)

Setting Password For Root User

Step 27: Let’s create one user and add it to the wheel group so it can also perform root tasks. So, to do that just follow the below piece of code. (The «wheel» is just the name of the group where normal users get admin rights after adding)

useradd -m -G wheel -s /bin/bash kanav

At the end of the above code, you can choose your name instead of kanav

Creating New User

Step 28: Now we have to build a user and added it to the wheel group but still we need to allow the wheel group for that we will first open visudo file.

EDITOR=nano visudo

Opening Visudo File

I have chosen a nano editor you can choose of your choice otherwise just go with the same.

Step 29: Now let’s edit the sudoers file which we have opened now. So we need to navigate the “wheel” and remove #. See the image for reference.

Editing Whell Group

Downloading and Installing GRUB in Linux

Step 30: Now we come to almost the end of our configuration with a very important step where we will install GRUB Bootloader so that when we restart our system we have the option to choose and boot our system.

  • Let’s download GRUB first by following the below code. (See the below image for reference)
pacman -S grub
  • Now after download, we will install it into our disk by following the command. (look over the below image for reference)
grub-install /dev/sda

Remember if your disk name is different during the partition then choose the same one. 

Downloading and Installing GRUB in Linux

Configuring GRUB Bootloader In Linux

Step 31: Now we will create a configuration file of the grub with the help of “mkconfig” utility.

grub-mkconfig -o /boot/grub/grub.cfg

Configuring GRUB Bootloader In Linux

Installing And Enabling Network Manager In Linux

Step 32: Now we will install Network Manager, which will install wifi and other important network drivers in our newly installed Arch system.

pacman -S networkmanager

Installing And Enabling Network Manager In Linux

Step 33: After install now we will enable Network Manager.

systemctl enable NetworkManager

Enabling Network Manager In Linux

Step 34: Now we are done with installation so we will now exit from the terminal and unmount our root partition and restart our system, So follow the below sequence one by one.

exit

umount -R /mnt

reboot

Exiting And Rebooting

Step 35: Now during reboot, our grub will open where it asks you to boot your Arch Linux. So just press Enter.

Booting Arch and Selecting From GRUB Menu

Step 36: Now after booting you will see an Arch. A login prompt open where you have to type your credentials. So just log in with your root id password which we have set.

Logging In A Installed Arch As A Root User

Step 37: Now we will set a password for our user which we previously created. I have created kanav so I am setting a password for it by using passwd command. 

passwd kanav

Setting Password for New User

Now we have completed the Arch Linux installation guide.

How to Install GUI in Arch Linux

Now we know how to install Arch but if you want to use GUI Interface then follow the below piece of code 

Step 38: Now we are in CLI (Command-line interface) so if you want GUI mode then we can download it. So let’s start with our Arch Linux desktop install process by below command

pacman -S xorg plasma plasma-wayland-session kde-applications console firefox

After executing this command it will ask you serval times for other inputs which you can just bypass by pressing «Enter»

It not only tells you how to install GUI in your system, but it also shows you how you can install applications in Arch. Here I have installed firefox and other pre-defined KDE applications also along with GUI.

Installing GUI Mode in Linux

Step 39: So, we have installed a GUI environment with KDE Plasma but you can also choose a desktop environment according to your choice like you can install gnome, Xorg etc.

Now let’s enable display drivers and reboot our system. So follow the below sequence of code one by one.

systemctl enable sddm

reboot

Enabling Display Drivers

Step 40: Now see it asking for id passwd in GUI Mode so just fill up your credentials.

How to Install GUI in Arch Linux

Step 41: Now after a few minutes you will see your desktop screen.

Logging In GUI Mode

Hi, techies thanks for reading this blog. I know it was long but I have tried to cover all steps in brief and other additional things from scratch. I hope the steps I guided in this blog will be helpful. In case you are stuck in between any step or you need any other help you can leave a comment at end of this blog or you can directly contact me at kanav@techofide.com

Commonly Asked Questions

Q1. Is Arch hard to install?

Ans. No, it just looks lengthy for a new person to install but I have made it very easy just follow this blog. In case you feel any help is required I will always there for your help you can directly contact me at kanav@techofide.com or you can also ask on my WhatsApp group.

Q2. Why is Arch better?

Ans. In the terms of flexibility, freedom to user and light-weighted experience. I feel it is better compared to another operating system if you want to use a light and smooth operating system. But it doesn’t mean it can replace other Linux operating systems.

Q3. How do you chroot in Arch?

Ans. It is very easy you just need to open a terminal and run «sudo arch-chroot» (use sudo if you are not in root) you can also view a demonstration by clicking on look onthe  Demonstration

Q4. Can a beginner use Arch Linux?

Ans. Yes, even I think it is a great choice if you start because only installation will give you the whole overview of the Linux architecture and important configuration files. After using it you will feel like a pro and other distributions like Ubuntu, Fedora, CentOS will be much easier for you to use. In short, it will clear all your concepts from scratch.

Q5. Which is better Arch Linux or Kali Linux?

Ans. I think this a very unfair comparison because both are different and made for different motives. Arch  has a motive of providing a flexible and light-weighted operating system where the user has full control over install and removal of all the components from scratch but on the other hand, Kali Linux is mostly used by hackers and Cyber Security experts. Kali came with many pre-installed hacking tools which also made Kali operating system heavy. 

Q6. Can I install Arch Linux?

Ans. Yes, I have made it very easy for you just follow the above steps carefully. I am assuring you it will be very easy to install Arch Linux after following the above-mentioned steps. In case you feel any error or difficulty you can directly contact me at kanav@techofide.com or you can also ask on my WhatsApp group.

Q7. How to install GUI on Arch Linux?

Ans. You can go to Step [38] & [39] of this blog by clicking on Go to Answer

Q8. Is Arch Linux worth it?

Ans. Actually, it depends upon the user, If you are a beginner and want to start learning then it absolutely worth it, but if you are a user who likes to use GUI based system then you might not like it. Most of the users who know about Linux servers are switching to Arch Linux.

Q9. How to install an application on Arch Linux?

Ans. It is easy to install an application on it, you can go with the pre-defined Pacman manager or you can allow snap to install any application or you can go for yourt for example if you want to install gedit with «snap» just run «sudo snap install gedit» or if you want to go with pre-defined Pacman manager then it will be like «sudo pacman -S PACKAGENAME»  You can also go for Yaourt (Yet Another User Repository Tool) is an advanced shell  tool for install in packages on Arch.

It is used to search, install and upgrade packages from AUR interactively, supp

Q10. Does Arch Linux have GUI?

Ans. No, it’s not coming by pre-defined but you can easily install it by running 2-3 commands, If you want to know that commands, you can go to Step [38] & [39] of this blog by clicking on Go to Answer

Related Blogs

  • How to Create Bootable USB | Linux Bootable USB | Windows Bootable USB
  • How to Become an Ethical Hacker | Techofide
  • What is Computer Network | Basics of Networking [With Practical Examples]
  • Boot Menu Option Keys For All Computers and Laptops | [Updated List 2021]
  • What is Metasploit Framework | What is Penetration Testing | How to use Metasploit
  • How to Install Metasploit on Windows and Linux | [Step by Step Guide]

Related Videos

  • How to install Arch Linux in 2023
  • How to Install Virtual Box in your System

Also Read

  • What is Graph in Data Structures? | Techofide
  • What is Keyword | What is Keyword Research | Techofide

Понравилась статья? Поделить с друзьями:
  • Как работает ирригатор для полости рта инструкция
  • Как работает ирригатор для полости рта инструкция
  • Инструкция к мультиварке supra mcs 4521
  • Инструкция к мультиварке supra mcs 4521
  • Метформин 750 инструкция по применению цена отзывы аналоги цена