|
|
Line 1: |
Line 1: |
| {{Article | | <noinclude> |
| |Author=Drobbins
| | {{InstallPart|процесс разбиения диска и создания файловых систем}} |
| |Next in Series=Linux Fundamentals, Part 2
| | </noinclude> |
| }} | | === Подготовка жесткого диска === |
| == Antes de Iinciar == | | |
| | В этой части мы научимся различным способам установки Funtoo Linux -- и загрузки с -- жесткого диска. |
| | |
| | ==== Введение ==== |
| | |
| | В прежние времена существовал лишь один способ загрузить PC-совместимый компьютер. Все наши дектопы и сервера имели стандартный PC BIOS, все наши харды использовали MBR и были разбиты используя схему разбивки MBR. Вот как это все было и нам это нравилось! |
| | |
| | Затем появились EFI и UEFI, встроенные программы нового образца наряду со схемой разбивки GPT, поддерживающая диски размером более 2.2TБ. Неожиданно, нам стали доступны различные способы установки и загрузки Линукс систем . То, что было единым методом, стало чем-то более сложным. |
| | |
| | Воспользуемся моментом и рассмотрим доступные способы конфигурации жесткого диска для загрузки Funtoo Linux. Данное Руководство рекомендует способ "по-старинке" , загрузка BIOS и использование MBR. Данный способ работает (за исключением редких случаев) и всесторонне поддерживается. И в этом нет ничего плохого. Если Ваш жесткий диск 2TБ или меньшего размера это не является препятствием для использования всего дискового пространства. |
| | |
| | Но, бывают ситуации когда метод "по-старинке" не является оптимальным. Если Ваш жесткий диск размером более 2TБ , MBR разбивка не сможет обеспечить доступ ко всему дисковому пространству. Это одна из причин. Вторая причина: существуют "PC" системы, которые более не поддерживают BIOS загрузку и форсируют UEFI загрузку. Из чувства сострадания к тем, кто попал в затруднение перед выбором, это Руководство также описывает установку и загрузку UEFI систем. |
| | |
| | Мы всё же рекомендуем разбивку "по-старинке". Загрузчик, который мы используем для загрузки Линукс в этом руководстве называется GRUB, таки образом мы называем метод как '''BIOS + GRUB (MBR)''' . Это традиционный способ установки на PC-совместимые компьютеры. |
| | |
| | Если Вам необходимо использование UEFI для загрузки, мы советуем не использовать MBR вообще, ввиду того, что некоторые системы поддерживают MBR, а некоторые нет. Вместо, мы советуем использование UEFI для загрузки GRUB, который, затем в свою очередь загрузит Линукс. Мы называем этот метод как '''UEFI + GRUB (GPT)'''. |
| | |
| | И да, есть еще несколько способов, некоторые из них задокументированы в [[Boot Methods]] . Обычно мы рекомендуем '''BIOS + GRUB (GPT)''' метод, но он ограничивается не столь широкой поддержкой со стороны комплектующих. |
| | |
| | '''Вопрос -- какой из методов использовать?''' Вот какой. |
| | |
| | ;Принцип 1 - "По-старинке": Если Вы можете успешно загрузить System Rescue CD и видите синее меню, то Вы используете BIOS, и скорее всего Вы можете загрузить Funtoo Linux используя BIOS. Итак, следуйте этому способу и используйте BIOS загрузку, кроме случаев Вам по-какой либо причине необходим UEFI, например если размер жесткого диска >2.2TБ. В этом случае следуйте Принцип 2. |
| | |
| | ;Принцип 2 - "Модерн": Если Вы можете успешно загрузить System Rescue CD и видите черно-белое меню -- поздравления, Ваша система поддерживает UEFI загрузку. Это значит, что Вы готовы установить Funtoo Linux к загрузке с помощью UEFI. Ваша система также может поддерживать загрузку BIOS, но попрбуйте UEFI для начала. Вы можете "покопаться" в настройках BIOS. |
| | |
| | ;Какая разница между "По-старинке" и "Модерн"?: Если Вы следуете MBR разбивке, Ваш <code>/boot</code> раздел будет отформатирован файловой системой ext2 , и Вы будете использовать <code>fdisk</code> для создания MBR разделов. Если Вы следуете "модерн", GPT разделам и UEFI загрузке, Ваш <code>/boot</code> раздел будет отформатирован в файловую систему vfat, поскольку это единственная файловая система поддерживаемая UEFI, и Вы будете использовать <code>gdisk</code> для создания GPT разделов. И Вы установите GRUB несколько иначе. Вот к чему сводится различие между методами. |
| | |
| | ;Имейте в виду: Для установки Funtoo Linux используя метод "модерн", Вы должны загрузить System Rescue CD в UEFI режиме -- и увидеть начальное черно-белое меню. В противном случае, UEFI не активно и Вы не сможете продолжить! |
| | |
| | {{Note|'''Некоторые материнские платы якобы поддерживают UEFI, но на самом деле нет.''' Исследуйте . К примеру, Award BIOS в моей Gigabyte GA-990FXA-UD7 rev 1.1 имеет возможность включить UEFI загрузку для CD/DVD. '''Этого не достаточно для обеспечения UEFI загрузки для жестких дисков и установки Funtoo Linux.''' UEFI должно поддерживать и сьемные носители (таким образом Вы сможете загрузить System Rescue CD используя UEFI) и жесткие диски (Вы можете загрузить Funtoo Linux.) Оказывается, что более поздние ревизии этой платы (rev 3.0) имеют новую версию BIOS который полностью поддерживает UEFI. Это приводит к третьему принципу -- знайте Ваши комплектующие.}} |
| | |
| | ==== Метод (BIOS/MBR) "По-старинке" ==== |
| | |
| | {{Note|Используйте данный метод при загрузке с помощью BIOS, и если System Rescue CD имеет начальное меню загрузки светло-голубое. Если Вы собираетесь использовать "модерн", [[#Метод (UEFI/GPT) "Модерн"|кликните здесь в меню UEFI/GPT.]]}} |
| | |
| | ===== Подготовка ===== |
| | |
| | Прежде чем начать , неплохо бы удостовериться, что Вы используете нужный диск для разбивки. Попробуйте эту комманду и проверьте, что <code>/dev/sda</code> тот самый диск, который Вы желаете разбить: |
|
| |
|
| === About this tutorial ===
| | <console> |
| Bem vindo ao "Linux fundamentals," o primeiro de quatro tutoriais desenvolvido para lhe preparar para o exame da Linux Professional Institute's 101 (LPI 101). Nesse tutorial, vamos lhe introduzir ao bash (o shell padrão do Linux), lhe mostrar como tirar vantagem dos comando padrões do Linux como like ls, cp, e mv, explicar inodes e hard links e links simbólicos, e muito mais. Ao final desse tutorial, você terá sólida base no Linux fundamentals e estará até mesmo pronto para começar a aprender algumas tarefas básicas de administração do sistema Linux. Ao final dessa série de tutoriais (oito ao todo), você terá conhecimento que você precisa para se tornar um administrador Linux e estará pronto para realizar uma certificação LPIC nível 1 da Linux Professional Institute se você escolher assim.
| | # ##i##fdisk -l /dev/sda |
|
| |
|
| Esse tutorial particular (Parte 1) é ideal para aqueles que são novos no Linux, ou para aqueles que querem rever ou melhorar seus entendimentos dos conceitos fundamentais do Linux como copiar e mover arquivos, criar symbolic e hard links, e utilizar comandos de processamento de texto padrão do Linux juntamente com pipelines e redirecionamento. Ao longo do caminho, compartilharemos um monte de sugestões, dicas, e truques para manter o tutorial robusto e prático, mesmo para aqueles com uma bom montante de experiencia anterior em Linux. Para iniciantes, muito desse será novo, mas usuários de Linux mais experientes podem achar esse tutorial ser um ótimo jeito de circundar suas habilidades fundamentais em Linux.
| | Disk /dev/sda: 640.1 GB, 640135028736 bytes, 1250263728 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 label type: gpt |
|
| |
|
| For those who have taken the release 1 version of this tutorial for reasons other than LPI exam preparation, you probably don't need to take this one. However, if you do plan to take the exams, you should strongly consider reading this revised tutorial.
| |
|
| |
|
| == Introducing bash ==
| | # Start End Size Type Name |
| === The shell ===
| | 1 2048 1250263694 596.2G Linux filesyste Linux filesystem |
| If you've used a Linux system, you know that when you log in, you are greeted by a prompt that looks something like this:
| | </console> |
| <pre>
| |
| $
| |
| </pre> | |
| The particular prompt that you see may look quite different. It may contain your systems host name, the name of the current working directory, or both. But regardless of what your prompt looks like, there's one thing that's certain. The program that printed that prompt is called a "shell," and it's very likely that your particular shell is a program called <span style="color:green">bash</span>.
| |
|
| |
|
| === Are you running bash? ===
| | Теперь, рекомендуем стереть существующие таблицы разделов MBR или GPT, которые могут помешать BIOS во время загрузки. Мы используем комманду <code>sgdisk</code>: |
| You can check to see if you're running <span style="color:green">bash</span> by typing:
| | {{fancywarning|Это необратимый процесс, который уничтожит все разделы! Вы предупреждены! Советуем сохранить критические данние перед этим.}} |
| <pre>
| |
| $ echo $SHELL
| |
| /bin/bash
| |
| </pre>
| |
| If the above line gave you an error or didn't respond similarly to our example, then you may be running a shell other than bash. In that case, most of this tutorial should still apply, but it would be advantageous for you to switch to <span style="color:green">bash</span> for the sake of preparing for the 101 exam.
| |
|
| |
|
| === About bash ===
| | <console> |
| Bash, an acronym for "Bourne-again shell," is the default shell on most Linux systems. The shell's job is to obey your commands so that you can interact with your Linux system. When you're finished entering commands, you may instruct the shell to exit or logout, at which point you'll be returned to a login prompt.
| | # ##i##sgdisk --zap-all /dev/sda |
|
| |
|
| By the way, you can also log out by pressing control-D at the bash prompt.
| | Creating new GPT entries. |
| | GPT data structures destroyed! You may now partition the disk using fdisk or |
| | other utilities. |
| | </console> |
|
| |
|
| === Using "cd" ===
| | Не стоит беспокоится об этом сообщении, так как комманда успешно выполнена: |
| As you've probably found, staring at your bash prompt isn't the most exciting thing in the world. So, let's start using bash to navigate around our file system. At the prompt, type the following (without the <span style="color:green">$</span>):
| |
| <pre>
| |
| $ cd /
| |
| </pre>
| |
| We've just told bash that you want to work in /, also known as the root directory; all the directories on the system form a tree, and / is considered the top of this tree, or the root. cd sets the directory where you are currently working, also known as the "current working directory."
| |
|
| |
|
| === Paths ===
| | <console> |
| To see bash's current working directory, you can type:
| | *************************************************************** |
| <pre> | | Found invalid GPT and valid MBR; converting MBR to GPT format |
| $ pwd
| | in memory. |
| /
| | *************************************************************** |
| </pre>
| | </console> |
| In the above example, the / argument to <span style="color:green">cd</span> is called a ''path''. It tells cd where we want to go. In particular, the / argument is an ''absolute'' path, meaning that it specifies a location relative to the root of the file system tree.
| |
|
| |
|
| === Absolute paths === | | ===== Разбивка диска ===== |
| Here are some other absolute paths:
| |
| <pre>
| |
| /dev
| |
| /usr
| |
| /usr/bin
| |
| /usr/local/bin
| |
| </pre>
| |
| As you can see, the one thing that all absolute paths have in common is that they begin with /. With a path of /usr/local/bin, we're telling cd to enter the / directory, then the usr directory under that, and then local and bin. Absolute paths are always evaluated by starting at / first.
| |
|
| |
|
| === Relative paths ===
| | Теперь мы используем <code>fdisk</code> для создания таблицы разделов MBR и самих разделов: |
| The other kind of path is called a ''relative path''. <span style="color:green">Bash</span>, <span style="color:green">cd</span>, and other commands always interpret these paths relative to the current directory. Relative paths never begin with a /. So, if we're in /usr:
| |
| <pre>
| |
| $ cd /usr
| |
| </pre> | |
| Then, we can use a relative path to change to the /usr/local/bin directory:
| |
| <pre>
| |
| $ cd local/bin
| |
| $ pwd
| |
| /usr/local/bin
| |
| </pre>
| |
|
| |
|
| === Using .. ===
| | <console> |
| Relative paths may also contain one or more .. directories. The .. directory is a special directory that points to the parent directory. So, continuing from the example above:
| | # ##i##fdisk /dev/sda |
| <pre> | | </console> |
| $ pwd
| |
| /usr/local/bin
| |
| $ cd ..
| |
| $ pwd
| |
| /usr/local | |
| </pre> | |
| As you can see, our current directory is now /usr/local. We were able to go "backwards" one directory, relative to the current directory that we were in.
| |
|
| |
|
| In addition, we can also add .. to an existing relative path, allowing us to go into a directory that's alongside one we are already in, for example:
| | В консоли <code>fdisk</code>, следуйте следующим шагам: |
| <pre> | |
| $ pwd
| |
| /usr/local
| |
| $ cd ../share
| |
| $ pwd
| |
| /usr/share
| |
| </pre> | |
|
| |
|
| === Relative path examples ===
| | '''Очистить таблицу разделов''': |
| Relative paths can get quite complex. Here are a few examples, all without the resultant target directory displayed. Try to figure out where you'll end up after typing these commands:
| |
| <pre>
| |
| $ cd /bin
| |
| $ cd ../usr/share/zoneinfo
| |
|
| |
|
| | <console> |
| | Command (m for help): ##i##o ↵ |
| | </console> |
|
| |
|
| $ cd /usr/X11R6/bin
| | '''Создать раздел 1''' (boot): |
| $ cd ../lib/X11
| |
|
| |
|
| | <console> |
| | Command (m for help): ##i##n ↵ |
| | Partition type (default p): ##i##↵ |
| | Partition number (1-4, default 1): ##i##↵ |
| | First sector: ##i##↵ |
| | Last sector: ##i##+128M ↵ |
| | </console> |
|
| |
|
| $ cd /usr/bin
| | '''Создать раздел 2''' (своп): |
| $ cd ../bin/../bin
| |
| </pre>
| |
| Now, try them out and see if you got them right :)
| |
|
| |
|
| === Understanding "." ===
| | <console> |
| Before we finish our coverage of cd, there are a few more things I need to mention. First, there is another special directory called ., which means "the current directory". While this directory isn't used with the cd command, it's often used to execute some program in the current directory, as follows:
| | Command (m for help): ##i##n ↵ |
| <pre>
| | Partition type (default p): ##i##↵ |
| $ ./myprog
| | Partition number (2-4, default 2): ##i##↵ |
| </pre> | | First sector: ##i##↵ |
| In the above example, the myprog executable residing in the current working directory will be executed.
| | Last sector: ##i##+2G ↵ |
| | Command (m for help): ##i##t ↵ |
| | Partition number (1,2, default 2): ##i## ↵ |
| | Hex code (type L to list all codes): ##i##82 ↵ |
| | </console> |
|
| |
|
| === cd and the home directory ===
| | '''Создать корневой раздел:''' |
| If we wanted to change to our home directory, we could type:
| |
| <pre>
| |
| $ cd
| |
| </pre>
| |
| With no arguments, cd will change to your home directory, which is /root for the superuser and typically /home/username for a regular user. But what if we want to specify a file in our home directory? Maybe we want to pass a file argument to the <span style="color:green">myprog</span> command. If the file lives in our home directory, we can type:
| |
| <pre>
| |
| $ ./myprog /home/drobbins/myfile.txt
| |
| </pre>
| |
| However, using an absolute path like that isn't always convenient. Thankfully, we can use the ~ (tilde) character to do the same thing:
| |
| <pre>
| |
| $ ./myprog ~/myfile.txt
| |
| </pre>
| |
|
| |
|
| === Other users' home directories ===
| | <console> |
| Bash will expand a lone ~ to point to your home directory, but you can also use it to point to other users' home directories. For example, if we wanted to refer to a file called fredsfile.txt in Fred's home directory, we could type:
| | Command (m for help): ##i##n ↵ |
| <pre>
| | Partition type (default p): ##i##↵ |
| $ ./myprog ~fred/fredsfile.txt
| | Partition number (3,4, default 3): ##i##↵ |
| </pre> | | First sector: ##i##↵ |
| | Last sector: ##i##↵ |
| | </console> |
|
| |
|
| == Using Linux Commands ==
| | '''Проверить таблицу разделов:''' |
|
| |
|
| === Introducing ls ===
| | <console> |
| Now, we'll take a quick look at the ls command. Very likely, you're already familiar with ls and know that typing it by itself will list the contents of the current working directory:
| | Command (m for help): ##i##p |
| <pre>
| |
| $ cd /usr
| |
| $ ls
| |
| X11R6 doc i686-pc-linux-gnu lib man sbin ssl
| |
| bin gentoo-x86 include libexec portage share tmp
| |
| distfiles i686-linux info local portage.old src
| |
| </pre> | |
| By specifying the -a option, you can see all of the files in a directory, including hidden files: those that begin with .. As you can see in the following example, ls -a reveals the . and .. special directory links:
| |
| <pre>
| |
| $ ls -a
| |
| . bin gentoo-x86 include libexec portage share tmp
| |
| .. distfiles i686-linux info local portage.old src
| |
| X11R6 doc i686-pc-linux-gnu lib man sbin ssl
| |
| </pre>
| |
|
| |
|
| === Long directory listings ===
| | Disk /dev/sda: 298.1 GiB, 320072933376 bytes, 625142448 sectors |
| You can also specify one or more files or directories on the <span style="color:green">ls</span> command line. If you specify a file, <span style="color:green">ls</span> will show that file only. If you specify a directory, <span style="color:green">ls</span> will show the ''contents'' of the directory. The -l option comes in very handy when you need to view permissions, ownership, modification time, and size information in your directory listing.
| | Units: sectors of 1 * 512 = 512 bytes |
| | Sector size (logical/physical): 512 bytes / 512 bytes |
| | I/O size (minimum/optimal): 512 bytes / 512 bytes |
| | Disklabel type: dos |
| | Disk identifier: 0x82abc9a6 |
|
| |
|
| In the following example, we use the -l option to display a full listing of my /usr directory.
| | Device Boot Start End Blocks Id System |
| <pre>
| | /dev/sda1 2048 264191 131072 83 Linux |
| $ ls -l /usr
| | /dev/sda2 264192 4458495 2097152 82 Linux swap / Solaris |
| drwxr-xr-x 7 root root 168 Nov 24 14:02 X11R6
| | /dev/sda3 4458496 625142447 310341976 83 Linux |
| drwxr-xr-x 2 root root 14576 Dec 27 08:56 bin
| | </console> |
| drwxr-xr-x 2 root root 8856 Dec 26 12:47 distfiles
| |
| lrwxrwxrwx 1 root root 9 Dec 22 20:57 doc -> share/doc
| |
| drwxr-xr-x 62 root root 1856 Dec 27 15:54 gentoo-x86
| |
| drwxr-xr-x 4 root root 152 Dec 12 23:10 i686-linux
| |
| drwxr-xr-x 4 root root 96 Nov 24 13:17 i686-pc-linux-gnu
| |
| drwxr-xr-x 54 root root 5992 Dec 24 22:30 include
| |
| lrwxrwxrwx 1 root root 10 Dec 22 20:57 info -> share/info
| |
| drwxr-xr-x 28 root root 13552 Dec 26 00:31 lib
| |
| drwxr-xr-x 3 root root 72 Nov 25 00:34 libexec
| |
| drwxr-xr-x 8 root root 240 Dec 22 20:57 local
| |
| lrwxrwxrwx 1 root root 9 Dec 22 20:57 man -> share/man
| |
| lrwxrwxrwx 1 root root 11 Dec 8 07:59 portage -> gentoo-x86/
| |
| drwxr-xr-x 60 root root 1864 Dec 8 07:55 portage.old
| |
| drwxr-xr-x 3 root root 3096 Dec 22 20:57 sbin
| |
| drwxr-xr-x 46 root root 1144 Dec 24 15:32 share
| |
| drwxr-xr-x 8 root root 328 Dec 26 00:07 src
| |
| drwxr-xr-x 6 root root 176 Nov 24 14:25 ssl
| |
| lrwxrwxrwx 1 root root 10 Dec 22 20:57 tmp -> ../var/tmp
| |
| </pre> | |
| The first column displays permissions information for each item in the listing. I'll explain how to interpret this information in a bit. The next column lists the number of links to each file system object, which we'll gloss over now but return to later. The third and fourth columns list the owner and group, respectively. The fifth column lists the object size. The sixth column is the "last modified" time or "mtime" of the object. The last column is the object's name. If the file is a symbolic link, you'll see a trailing -> and the path to which the symbolic link points.
| |
|
| |
|
| === Looking at directories ===
| | '''Записать таблицу разделов на диск:''' |
| Sometimes, you'll want to look at a directory, rather than inside it. For these situations, you can specify the <span style="color:green">-d</span> option, which will tell ls to look at any directories that it would normally look inside:
| |
| <pre>
| |
| $ ls -dl /usr /usr/bin /usr/X11R6/bin ../share
| |
| drwxr-xr-x 4 root root 96 Dec 18 18:17 ../share
| |
| drwxr-xr-x 17 root root 576 Dec 24 09:03 /usr
| |
| drwxr-xr-x 2 root root 3192 Dec 26 12:52 /usr/X11R6/bin
| |
| drwxr-xr-x 2 root root 14576 Dec 27 08:56 /usr/bin
| |
| </pre>
| |
|
| |
|
| === Recursive and inode listings ===
| | <console> |
| So you can use <span style="color:green">-d</span> to look at a directory, but you can also use <span style="color:green">-R</span> to do the opposite: not just look inside a directory, but recursively look inside all the files and directories inside that directory! We won't include any example output for this option (since it's generally voluminous), but you may want to try a few <span style="color:green">ls -R</span> and <span style="color:green">ls -Rl</span> commands to get a feel for how this works.
| | Command (m for help): ##i##w |
| | </console> |
|
| |
|
| Finally, the <span style="color:green">-i</span> ls option can be used to display the inode numbers of the file system objects in the listing:
| | Ваша новая таблица разделов будет записана на диск. |
| <pre>
| |
| $ ls -i /usr
| |
| 1409 X11R6 314258 i686-linux 43090 libexec 13394 sbin
| |
| 1417 bin 1513 i686-pc-linux-gnu 5120 local 13408 share
| |
| 8316 distfiles 1517 include 776 man 23779 src
| |
| 43 doc 1386 info 93892 portage 36737 ssl
| |
| 70744 gentoo-x86 1585 lib 5132 portage.old 784 tmp
| |
| </pre>
| |
|
| |
|
| === Understanding inodes ===
| | {{Note|Вы завершили создание разделов! Теперь, перейдите к [[#Создание файловых систем|Создание файловых систем]].}} |
| Every object on a file system is assigned a unique index, called an inode number. This might seem trivial, but understanding inodes is essential to understanding many file system operations. For example, consider the . and .. links that appear in every directory. To fully understand what a .. directory actually is, we'll first take a look at /usr/local's inode number:
| |
| <pre>
| |
| $ ls -id /usr/local
| |
| 5120 /usr/local
| |
| </pre>
| |
| The /usr/local directory has an inode number of 5120. Now, let's take a look at the inode number of /usr/local/bin/..:
| |
| <pre>
| |
| $ ls -id /usr/local/bin/..
| |
| 5120 /usr/local/bin/..
| |
| </pre>
| |
| As you can see, /usr/local/bin/.. has the same inode number as /usr/local! Here's how we can come to grips with this shocking revelation. In the past, we've considered /usr/local to be the directory itself. Now, we discover that inode 5120 is in fact the directory, and we have found two directory entries (called "links") that point to this inode. Both /usr/local and /usr/local/bin/.. are links to inode 5120. Although inode 5120 only exists in one place on disk, multiple things link to it. Inode 5120 is the actual entry on disk.
| |
|
| |
|
| In fact, we can see the total number of times that inode 5120 is referenced by using the <pre>ls -dl</pre> command:
| | ==== Метод (UEFI/GPT) "Модерн" ==== |
| <pre>
| |
| $ ls -dl /usr/local
| |
| drwxr-xr-x 8 root root 240 Dec 22 20:57 /usr/local
| |
| </pre>
| |
| If we take a look at the second column from the left, we see that the directory /usr/local (inode 5120) is referenced eight times. On my system, here are the various paths that reference this inode:
| |
| <pre>
| |
| /usr/local
| |
| /usr/local/.
| |
| /usr/local/bin/..
| |
| /usr/local/games/..
| |
| /usr/local/lib/..
| |
| /usr/local/sbin/..
| |
| /usr/local/share/..
| |
| /usr/local/src/..
| |
| </pre>
| |
|
| |
|
| === mkdir ===
| | {{Note|Используйте данный метод при загрузке с помощью UEFI, и если System Rescue CD имеет начальное меню загрузки черно-белого цвета. Если оно было светло-голубого цвета, этот метод не будет работать.}} |
| Let's take a quick look at the <span style="color:green">mkdir</span> command, which can be used to create new directories. The following example creates three new directories, tic, tac, and toe, all under /tmp:
| |
| <pre>
| |
| $ cd /tmp
| |
| $ mkdir tic tac toe
| |
| </pre>
| |
| By default, the <span style="color:green">mkdir</span> command doesn't create parent directories for you; the entire path up to the next-to-last element needs to exist. So, if you want to create the directories '''won/der/ful''', you'd need to issue three separate <span style="color:green">mkdir</span> commands:
| |
| <pre>
| |
| $ mkdir won/der/ful
| |
| mkdir: cannot create directory `won/der/ful': No such file or directory
| |
| $ mkdir won
| |
| $ mkdir won/der
| |
| $ mkdir won/der/ful
| |
| </pre>
| |
| However, mkdir has a handy -p option that tells mkdir to create any missing parent directories, as you can see here:
| |
| <pre>
| |
| $ mkdir -p easy/as/pie
| |
| </pre>
| |
| All in all, pretty straightforward. To learn more about the mkdir command, type <span style="color:green">man mkdir</span> to read the manual page. This will work for nearly all commands covered here (for example, <span style="color:green">man ls</span>), except for <span style="color:green">cd</span>, which is built-in to bash.
| |
|
| |
|
| === touch ===
| | Комманда <tt>gdisk</tt> используется для создания таблицы разделов GPT . Измените размеры в соответсвии Вашим требованиям, хотя приведенные ниже размеры будут работать для большинства пользователей. Запустите <code>gdisk</code>: |
| Now, we're going to take a quick look at the <span style="color:green">cp</span> and <span style="color:green">mv</span> commands, used to copy, rename, and move files and directories. To begin this overview, we'll first use the <span style="color:green">touch</span> command to create a file in /tmp:
| |
| <pre>
| |
| $ cd /tmp
| |
| $ touch copyme
| |
| </pre>
| |
| The touch command updates the "mtime" of a file if it exists (recall the sixth column in <span style="color:green">ls -l</span> output). If the file doesn't exist, then a new, empty file will be created. You should now have a '''/tmp/copyme''' file with a size of zero.
| |
|
| |
|
| === echo ===
| | <console> |
| Now that the file exists, let's add some data to the file. We can do this using the echo command, which takes its arguments and prints them to standard output. First, the echo command by itself:
| | # ##i##gdisk |
| <pre>
| | </console> |
| $ echo "firstfile"
| |
| firstfile
| |
| </pre>
| |
| Now, the same echo command with output redirection:
| |
| <pre>
| |
| $ echo "firstfile" > copyme
| |
| </pre>
| |
| The greater-than sign tells the shell to write echo's output to a file called copyme. This file will be created if it doesn't exist, and will be overwritten if it does exist. By typing <span style="color:green">ls -l</span>, we can see that the copyme file is 10 bytes long, since it contains the word firstfile and the newline character:
| |
| <pre>
| |
| $ ls -l copyme
| |
| -rw-r--r-- 1 root root 10 Dec 28 14:13 copyme
| |
| </pre> | |
|
| |
|
| === cat and cp ===
| | В консоли <tt>gdisk</tt>, следуйте следующим шагам: |
| To display the contents of the file on the terminal, use the cat command:
| |
| <pre>
| |
| $ cat copyme
| |
| firstfile
| |
| </pre>
| |
| Now, we can use a basic invocation of the <span style="color:green">cp</span> command to create a copiedme file from the original copyme file:
| |
| <pre> | |
| $ cp copyme copiedme
| |
| </pre> | |
| Upon investigation, we find that they are truly separate files; their inode numbers are different:
| |
| <pre>
| |
| $ ls -i copyme copiedme
| |
| 648284 copiedme 650704 copyme
| |
| </pre>
| |
|
| |
|
| === mv ===
| | '''Создайте новую пустую таблицу разделов''' (Это уничтожит данные при сохранении на диск): |
| Now, let's use the <span style="color:green">mv</span> command to rename "copiedme" to "movedme". The inode number will remain the same; however, the filename that points to the inode will change.
| |
| <pre>
| |
| $ mv copiedme movedme
| |
| $ ls -i movedme
| |
| 648284 movedme
| |
| </pre>
| |
| A moved file's inode number will remain the same as long as the destination file resides on the same file system as the source file. We'll take a closer look at file systems in [[Linux Fundamentals, Part 3]] of this tutorial series.
| |
|
| |
|
| While we're talking about <span style="color:green">mv</span>, let's look at another way to use this command. <span style="color:green">mv</span>, in addition to allowing us to rename files, also allows us to move one or more files to another location in the directory hierarchy. For example, to move '''/var/tmp/myfile.txt''' to '''/home/drobbins''' (which happens to be my home directory,) I could type:
| | <console> |
| <pre>
| | Command: ##i##o ↵ |
| $ mv /var/tmp/myfile.txt /home/drobbins
| | This option deletes all partitions and creates a new protective MBR. |
| </pre>
| | Proceed? (Y/N): ##i##y ↵ |
| After typing this command, myfile.txt will be moved to '''/home/drobbins/myfile.txt'''. And if '''/home/drobbins''' is on a different file system than /var/tmp, the <span style="color:green">mv</span> command will handle the copying of myfile.txt to the new file system and erasing it from the old file system. As you might guess, when myfile.txt is moved between file systems, the myfile.txt at the new location will have a new inode number. This is because every file system has its own independent set of inode numbers.
| | </console> |
|
| |
|
| We can also use the <span style="color:green">mv</span> command to move multiple files to a single destination directory. For example, to move myfile1.txt and myarticle3.txt to /home/drobbins, I could type:
| | '''Создайте раздел 1''' (загрузочный): |
| <pre>
| |
| $ mv /var/tmp/myfile1.txt /var/tmp/myarticle3.txt /home/drobbins
| |
| </pre>
| |
|
| |
|
| == Creating Links and Removing Files ==
| | <console> |
| | Command: ##i##n ↵ |
| | Partition Number: ##i##1 ↵ |
| | First sector: ##i##↵ |
| | Last sector: ##i##+500M ↵ |
| | Hex Code: ##i##↵ |
| | </console> |
|
| |
|
| === Hard links ===
| | '''Создайте раздел 2''' (своп): |
| We've mentioned the term "link" when referring to the relationship between directory entries (the "names" we type) and inodes (the index numbers on the underlying file system that we can usually ignore.) There are actually two kinds of links available on Linux. The kind we've discussed so far are called hard links. A given inode can have any number of hard links, and the inode will persist on the file system until all the hard links disappear. When the last hard link disappears and no program is holding the file open, Linux will delete the file automatically. New hard links can be created using the <span style="color:green">ln</span> command:
| |
| <pre>
| |
| $ cd /tmp
| |
| $ touch firstlink
| |
| $ ln firstlink secondlink
| |
| $ ls -i firstlink secondlink
| |
| 15782 firstlink 15782 secondlink
| |
| </pre>
| |
| As you can see, hard links work on the inode level to point to a particular file. On Linux systems, hard links have several limitations. For one, you can only make hard links to files, not directories. That's right; even though . and .. are system-created hard links to directories, you (even as the "root" user) aren't allowed to create any of your own. The second limitation of hard links is that they can't span file systems; which would be the case if the file systems are on separate disk partitions. This means that you can't create a link from /usr/bin/bash to /bin/bash if your / and /usr directories exist on separate disk partitions.
| |
|
| |
|
| === Symbolic links ===
| | <console> |
| | Command: ##i##n ↵ |
| | Partition Number: ##i##2 ↵ |
| | First sector: ##i##↵ |
| | Last sector: ##i##+4G ↵ |
| | Hex Code: ##i##8200 ↵ |
| | </console> |
|
| |
|
| In practice, symbolic links (or symlinks) are used more often than hard links. Symlinks are a special file type where the link refers to another file by name, rather than directly to the inode. Symlinks do not prevent a file from being deleted; if the target file disappears, then the symlink will just be unusable, or broken.
| | '''Создайте раздел 3''' (корневой): |
|
| |
|
| A symbolic link can be created by passing the -s option to <span style="color:green">ln</span>.
| | <console> |
| <pre>
| | Command: ##i##n ↵ |
| $ ln -s secondlink thirdlink
| | Partition Number: ##i##3 ↵ |
| $ ls -l firstlink secondlink thirdlink
| | First sector: ##i##↵ |
| -rw-rw-r-- 2 agriffis agriffis 0 Dec 31 19:08 firstlink
| | Last sector: ##i##↵##!i## (for rest of disk) |
| -rw-rw-r-- 2 agriffis agriffis 0 Dec 31 19:08 secondlink
| | Hex Code: ##i##↵ |
| lrwxrwxrwx 1 agriffis agriffis 10 Dec 31 19:39 thirdlink -> secondlink
| | </console> |
| </pre>
| |
| Symbolic links can be distinguished in <span style="color:green">ls -l</span> output from normal files in three ways. First, notice that the first column contains an l character to signify the symbolic link. Second, the size of the symbolic link is the number of characters in the target (secondlink, in this case). Third, the last column of the output displays the target filename preceded by a cute little ->.
| |
|
| |
|
| === Symlinks in-depth ===
| | По пути Вы можете набрать "<tt>p</tt>" и нажать Enter для просмотра текущей таблицы разделов. Если Вы допустили ошибку, наберите "<tt>d</tt>" для удаления созданного раздела. Если Вы удовлетворены Вашей схемой разделов, наберите "<tt>w</tt>" для записи таблицы на диск: |
| Symbolic links are generally more flexible than hard links. You can create a symbolic link to any type of file system object, including directories. And because the implementation of symbolic links is based on paths (not inodes), it's perfectly fine to create a symbolic link that points to an object on another physical file system; that is, a different disk partition. However, this fact can also make symbolic links tricky to understand.
| |
|
| |
|
| Consider a situation where we want to create a link in /tmp that points to /usr/local/bin. Should we type this:
| | '''Записать таблицу разделов на диск''': |
| <pre>
| |
| $ ln -s /usr/local/bin bin1
| |
| $ ls -l bin1
| |
| lrwxrwxrwx 1 root root 14 Jan 1 15:42 bin1 -> /usr/local/bin
| |
| </pre>
| |
| Or alternatively:
| |
| <pre>
| |
| $ ln -s ../usr/local/bin bin2
| |
| $ ls -l bin2
| |
| lrwxrwxrwx 1 root root 16 Jan 1 15:43 bin2 -> ../usr/local/bin
| |
| </pre>
| |
| As you can see, both symbolic links point to the same directory. However, if our second symbolic link is ever moved to another directory, it will be "broken" because of the relative path:
| |
| <pre>
| |
| $ ls -l bin2
| |
| lrwxrwxrwx 1 root root 16 Jan 1 15:43 bin2 -> ../usr/local/bin
| |
| $ mkdir mynewdir
| |
| $ mv bin2 mynewdir
| |
| $ cd mynewdir
| |
| $ cd bin2
| |
| bash: cd: bin2: No such file or directory
| |
| </pre>
| |
| Because the directory /tmp/usr/local/bin doesn't exist, we can no longer change directories into bin2; in other words, bin2 is now broken.
| |
|
| |
|
| For this reason, it is sometimes a good idea to avoid creating symbolic links with relative path information. However, there are many cases where relative symbolic links come in handy. Consider an example where you want to create an alternate name for a program in /usr/bin:
| | <console> |
| <pre> | | Command: ##i##w ↵ |
| # ls -l /usr/bin/keychain | | Do you want to proceed? (Y/N): ##i##Y ↵ |
| -rwxr-xr-x 1 root root 10150 Dec 12 20:09 /usr/bin/keychain
| | </console> |
| </pre>
| |
| As the root user, you may want to create an alternate name for "keychain", such as "kc". In this example, we have root access, as evidenced by our bash prompt changing to "#". We need root access because normal users aren't able to create files in /usr/bin. As root, we could create an alternate name for keychain as follows:
| |
| <pre>
| |
| # cd /usr/bin | |
| # ln -s /usr/bin/keychain kc | |
| # ls -l keychain | |
| -rwxr-xr-x 1 root root 10150 Dec 12 20:09 /usr/bin/keychain
| |
| # ls -l kc | |
| lrwxrwxrwx 1 root root 17 Mar 27 17:44 kc -> /usr/bin/keychain
| |
| </pre> | |
| In this example, we created a symbolic link called kc that points to the file /usr/bin/keychain.
| |
|
| |
|
| While this solution will work, it will create problems if we decide that we want to move both files, /usr/bin/keychain and /usr/bin/kc to /usr/local/bin:
| | Таблица разделов будет записана на диск и <tt>gdisk</tt> завершит работу. |
| <pre> | |
| # mv /usr/bin/keychain /usr/bin/kc /usr/local/bin
| |
| # ls -l /usr/local/bin/keychain
| |
| -rwxr-xr-x 1 root root 10150 Dec 12 20:09 /usr/local/bin/keychain
| |
| # ls -l /usr/local/bin/kc
| |
| lrwxrwxrwx 1 root root 17 Mar 27 17:44 kc -> /usr/bin/keychain
| |
| </pre> | |
| Because we used an absolute path in our symbolic link, our kc symlink is still pointing to /usr/bin/keychain, which no longer exists since we moved /usr/bin/keychain to /usr/local/bin.
| |
|
| |
|
| That means that kc is now a broken symlink. Both relative and absolute paths in symbolic links have their merits, and you should use a type of path that's appropriate for your particular application. Often, either a relative or absolute path will work just fine. The following example would have worked even after both files were moved:
| | Теперь GPT/GUID разделы созданы, и будут показаны как ''блочные утройства'' в Linux: |
| <pre>
| |
| # cd /usr/bin
| |
| # ln -s keychain kc
| |
| # ls -l kc
| |
| lrwxrwxrwx 1 root root 8 Jan 5 12:40 kc -> keychain
| |
| # mv keychain kc /usr/local/bin
| |
| # ls -l /usr/local/bin/keychain
| |
| -rwxr-xr-x 1 root root 10150 Dec 12 20:09 /usr/local/bin/keychain
| |
| # ls -l /usr/local/bin/kc
| |
| lrwxrwxrwx 1 root root 17 Mar 27 17:44 kc -> keychain
| |
| </pre>
| |
| Now, we can run the keychain program by typing /usr/local/bin/kc. /usr/local/bin/kc points to the program keychain in the same directory as kc.
| |
|
| |
|
| === rm ===
| | * <tt>/dev/sda1</tt>, будет использоваться для <tt>/boot</tt>, загрузочный раздел |
| Now that we know how to use cp, mv, and ln, it's time to learn how to remove objects from the file system. Normally, this is done with the rm command. To remove files, simply specify them on the command line:
| | * <tt>/dev/sda2</tt>, будет использоваться как своп , и |
| <pre> | | * <tt>/dev/sda3</tt>, корневой раздел. |
| $ cd /tmp
| |
| $ touch file1 file2
| |
| $ ls -l file1 file2
| |
| -rw-r--r-- 1 root root 0 Jan 1 16:41 file1
| |
| -rw-r--r-- 1 root root 0 Jan 1 16:41 file2
| |
| $ rm file1 file2
| |
| $ ls -l file1 file2
| |
| ls: file1: No such file or directory
| |
| ls: file2: No such file or directory
| |
| </pre> | |
| Note that under Linux, once a file is rm'ed, it's typically gone forever. For this reason, many junior system administrators will use the -i option when removing files. The -i option tells rm to remove all files in interactive mode -- that is, prompt before removing any file. For example:
| |
| <pre> | |
| $ rm -i file1 file2
| |
| rm: remove regular empty file `file1'? y
| |
| rm: remove regular empty file `file2'? y
| |
| </pre> | |
| In the above example, the rm command prompted whether or not the specified files should *really* be deleted. In order for them to be deleted, I had to type "y" and Enter twice. If I had typed "n", the file would not have been removed. Or, if I had done something really wrong, I could have typed Control-C to abort the rm -i command entirely -- all before it is able to do any potential damage to my system.
| |
|
| |
|
| If you are still getting used to the rm command, it can be useful to add the following line to your ~/.bashrc file using your favorite text editor, and then log out and log back in. Then, any time you type rm, the bash shell will convert it automatically to an rm -i command. That way, rm will always work in interactive mode:
| | ==== Создание файловых систем ==== |
| <pre>
| |
| alias rm="rm -i"
| |
| </pre>
| |
|
| |
|
| === rmdir ===
| | {{Note|Данная часть рассматривает как BIOS ''так и'' UEFI установки. Не пропускайте раздел!}} |
| To remove directories, you have two options. You can remove all the objects inside the directory and then use <span style="color:green">rmdir</span> to remove the directory itself:
| |
| <pre>
| |
| $ mkdir mydir
| |
| $ touch mydir/file1
| |
| $ rm mydir/file1
| |
| $ rmdir mydir
| |
| </pre>
| |
| This method is commonly referred to as "directory removal for suckers." All real power users and administrators worth their salt use the much more convenient <span style="color:green">rm -rf</span> command, covered next.
| |
|
| |
|
| The best way to remove a directory is to use the ''recursive force'' options of the rm command to tell rm to remove the directory you specify, as well as all objects contained in the directory:
| | Прежде чем Ваши только что созданные разделы могут быть использованы, блочные устройства должны быть инициализированы метаданными файловой системы. Данный процесс известен как ''создание файловой системы''. После этого блочные устройства могут быть смонтированы и использоваться для хранения данных . |
| <pre>
| |
| $ rm -rf mydir
| |
| </pre>
| |
| Generally, rm -rf is the preferred method of removing a directory tree. Be very careful when using rm -rf, since its power can be used for both good and evil :)
| |
|
| |
|
| == Using Wild cards ==
| | Будем проще. Используете разделы MBR, метод "по-старинке" ? Если да, давайте создадим файловую систему ext2 на /dev/sda1: |
|
| |
|
| === Introducing Wild cards ===
| | <console> |
| In your day-to-day Linux use, there are many times when you may need to perform a single operation (such as rm) on many file system objects at once. In these situations, it can often be cumbersome to type in many files on the command line:
| | # ##i##mkfs.ext2 /dev/sda1 |
| <pre> | | </console> |
| $ rm file1 file2 file3 file4 file5 file6 file7 file8
| |
| </pre>
| |
| To solve this problem, you can take advantage of Linux' built-in wild card support. This support, also called "globbing" (for historical reasons), allows you to specify multiple files at once by using a wildcard pattern. Bash and other Linux commands will interpret this pattern by looking on disk and finding any files that match it. So, if you had files file1 through file8 in the current working directory, you could remove these files by typing:
| |
| <pre>
| |
| $ rm file[1-8]
| |
| </pre>
| |
| Or if you simply wanted to remove all files whose names begin with file as well as any file named file, you could type:
| |
| <pre>
| |
| $ rm file*
| |
| </pre> | |
| The * wildcard matches any character or sequence of characters, or even "no character." Of course, glob wildcards can be used for more than simply removing files, as we'll see in the next panel.
| |
|
| |
|
| === Understanding non-matches ===
| | Если Вы используете разделы GPT для UEFI, метод "модерн", Вам нужно создать файловую систему FAT32 на /dev/sda1, поскольку это единственная поддерживамая UEFI фаловая система: |
| If you wanted to list all the file system objects in /etc beginning with g as well as any file called g, you could type:
| |
| <pre>
| |
| $ ls -d /etc/g*
| |
| /etc/gconf /etc/ggi /etc/gimp /etc/gnome /etc/gnome-vfs-mime-magic /etc/gpm /etc/group /etc/group-
| |
| </pre>
| |
| Now, what happens if you specify a pattern that doesn't match any file system objects? In the following example, we try to list all the files in /usr/bin that begin with asdf and end with jkl, including potentially the file asdfjkl:
| |
| <pre>
| |
| $ ls -d /usr/bin/asdf*jkl
| |
| ls: /usr/bin/asdf*jkl: No such file or directory
| |
| </pre>
| |
| Here's what happened. Normally, when we specify a pattern, that pattern matches one or more files on the underlying file system, and ''bash replaces the pattern with a space-separated list of all matching objects''. However, when the pattern doesn't produce any matches, ''bash leaves the argument, wild cards and all, as-is''. So, then ls can't find the file /usr/bin/asdf*jkl and it gives us an error. The operative rule here is that ''glob patterns are expanded only if they match objects in the file system''. Otherwise they remain as is and are passed literally to the program you're calling.
| |
|
| |
|
| === Wild card syntax: * and ? ===
| | <console> |
| Now that we've seen how globbing works, we should look at wild card syntax. You can use special characters for wild card expansion:
| | # ##i##mkfs.vfat -F 32 /dev/sda1 |
| | </console> |
|
| |
|
| <nowiki>*</nowiki> will match zero or more characters. It means "anything can go here, including nothing". Examples:
| | Теперь, создадим своп раздел. Он будет использоваться как дисковая виртуальная память для системы Funtoo Linux. |
|
| |
|
| * /etc/g* matches all files in /etc that begin with g, or a file called g.
| | Вы не будете создавать никакой файловой системы на своп разделе, поскольку он не используется для хранения каких-либо данных. Но необходимо инициализировать своп коммандой <code>mkswap</code>. Далее мы используем комманду <code>swapon</code> для незамедлительной активации своп-раздела в окружении живого диска live CD, в случае необходимости доступа к своп во время установки: |
| * /tmp/my*1 matches all files in /tmp that begin with my and end with 1, including the file my1.
| |
|
| |
|
| ? matches any single character. Examples:
| | <console> |
| | # ##i##mkswap /dev/sda2 |
| | # ##i##swapon /dev/sda2 |
| | </console> |
|
| |
|
| * myfile? matches any file whose name consists of myfile followed by a single character
| | Теперь, нам необходимо создать корневую файловую систему. Здесь будет жить Ваш Funtoo Linux. Обычно мы рекоммендуем ext4 или XFS. Если Вы не уверены, выбиайте ext4. Вот как создать файловую систему ext4: |
| * /tmp/notes?txt would match both /tmp/notes.txt and /tmp/notes_txt, if they exist
| |
|
| |
|
| === Wild card syntax: [] ===
| | <console> |
| This wild card is like a ?, but it allows more specificity. To use this wild card, place any characters you'd like to match inside the []. The resultant expression will match a single occurrence of any of these characters. You can also use - to specify a range, and even combine ranges. Examples:
| | # ##i##mkfs.ext4 /dev/sda3 |
| | </console> |
|
| |
|
| * myfile[12] will match myfile1 and myfile2. The wild card will be expanded as long as at least one of these files exists in the current directory.
| | ...и вот как создать файловую систему XFS, если это Ваш выбор для корневой системы: |
| * [Cc]hange[Ll]og will match Changelog, ChangeLog, changeLog, and changelog. As you can see, using bracket wild cards can be useful for matching variations in capitalization.
| |
| * ls /etc/[0-9]* will list all files in /etc that begin with a number.
| |
| * ls /tmp/[A-Za-z]* will list all files in /tmp that begin with an upper or lower-case letter.
| |
|
| |
|
| The [!] construct is similar to the [] construct, except rather than matching any characters inside the brackets, it'll match any character, as long as it is not listed between the [! and ]. Example:
| | <console> |
| | # ##i##mkfs.xfs /dev/sda3 |
| | </console> |
|
| |
|
| * rm myfile[!9] will remove all files named myfile plus a single character, except for myfile9
| | Your filesystems (and swap) have all now been initialized, so that that can be mounted (attached to your existing directory heirarchy) and used to store files. We are ready to begin installing Funtoo Linux on these brand-new filesystems. |
|
| |
|
| === Wild card caveats ===
| | {{fancywarning|1= |
| Here are some caveats to watch out for when using wild cards. Since bash treats wild card-related characters (?, [, ], and *) specially, you need to take special care when typing in an argument to a command that contains these characters. For example, if you want to create a file that contains the string [fo]*, the following command may not do what you want:
| | When deploying an OpenVZ host, please use ext4 exclusively. The Parallels development team tests extensively with ext4, and modern versions of <code>openvz-rhel6-stable</code> are '''not''' compatible with XFS, and you may experience kernel bugs. |
| <pre>
| | }} |
| $ echo [fo]* > /tmp/mynewfile.txt
| |
| </pre>
| |
| If the pattern [fo]* matches any files in the current working directory, then you'll find the names of those files inside /tmp/mynewfile.txt rather than a literal [fo]* like you were expecting. The solution? Well, one approach is to surround your characters with single quotes, which tell bash to perform absolutely no wild card expansion on them:
| |
| <pre>
| |
| $ echo '[fo]*' > /tmp/mynewfile.txt
| |
| </pre>
| |
| Using this approach, your new file will contain a literal [fo]* as expected. Alternatively, you could use backslash escaping to tell bash that [, ], and * should be treated literally rather than as wild cards:
| |
| <pre> | |
| $ echo \[fo\]\* > /tmp/mynewfile.txt
| |
| </pre> | |
| Both approaches (single quotes and backslash escaping) have the same effect. Since we're talking about backslash expansion, now would be a good time to mention that in order to specify a literal \, you can either enclose it in single quotes as well, or type \\ instead (it will be expanded to \).
| |
| {{fancynote|Double quotes will work similarly to single quotes, but will still allow bash to do some limited expansion. Therefore, single quotes are your best bet when you are truly interested in passing literal text to a command. For more information on wild card expansion, type man 7 glob. For more information on quoting in bash, type man 8 glob and read the section titled QUOTING. If you're planning to take the LPI exams, consider this a homework assignment :)}}
| |
|
| |
|
| == Summary and Resources == | | ==== Mounting filesystems ==== |
|
| |
|
| === Summary ===
| | Mount the newly-created filesystems as follows, creating <code>/mnt/funtoo</code> as the installation mount point: |
| Congratulations; you've reached the end of our review of Linux fundamentals! I hope that it has helped you to firm up your foundational Linux knowledge. The topics you've learned here, including the basics of bash, basic Linux commands, links, and wild cards, have laid the groundwork for our next tutorial on basic administration, in which we'll cover topics like regular expressions, ownership and permissions, user account management, and more.
| |
|
| |
|
| By continuing in this tutorial series, you'll soon be ready to attain your LPIC Level 1 Certification from the Linux Professional Institute. Speaking of LPIC certification, if this is something you're interested in, then we recommend that you study the Resources in the next panel, which have been carefully selected to augment the material covered in this tutorial.
| | <console> |
| | # ##i##mkdir /mnt/funtoo |
| | # ##i##mount /dev/sda3 /mnt/funtoo |
| | # ##i##mkdir /mnt/funtoo/boot |
| | # ##i##mount /dev/sda1 /mnt/funtoo/boot |
| | </console> |
|
| |
|
| === Resources ===
| | Optionally, if you have a separate filesystem for <code>/home</code> or anything else: |
| Be sure to read the other articles in this series:
| |
| *[[Linux Fundamentals, Part 2]]
| |
| *[[Linux Fundamentals, Part 3]]
| |
| *[[Linux Fundamentals, Part 4]]
| |
|
| |
|
| In the "Bash by Example" article series, Daniel shows you how to use bash programming constructs to write your own bash scripts. This series (particularly Parts 1 and 2) will be good preparation for the LPIC Level 1 exam:
| | <console> |
| * [[Bash by Example, Part 1]]: Fundamental programming in the Bourne-again shell
| | # ##i##mkdir /mnt/funtoo/home |
| * [[Bash by Example, Part 2]]: More bash programming fundamentals
| | # ##i##mount /dev/sda4 /mnt/funtoo/home |
| * [[Bash by Example, Part 3]]: Exploring the ebuild system
| | </console> |
|
| |
|
| | If you have <code>/tmp</code> or <code>/var/tmp</code> on a separate filesystem, be sure to change the permissions of the mount point to be globally-writeable after mounting, as follows: |
|
| |
|
| __NOTOC__
| | <console> |
| [[Category:Linux Core Concepts]]
| | # ##i##chmod 1777 /mnt/funtoo/tmp |
| [[Category:Articles]]
| | </console> |
| {{ArticleFooter}}
| |
Note
This is a template that is used as part of the Installation instructions which covers: процесс разбиения диска и создания файловых систем. Templates are being used to allow multiple variant install guides that use most of the same re-usable parts.
Подготовка жесткого диска
В этой части мы научимся различным способам установки Funtoo Linux -- и загрузки с -- жесткого диска.
Введение
В прежние времена существовал лишь один способ загрузить PC-совместимый компьютер. Все наши дектопы и сервера имели стандартный PC BIOS, все наши харды использовали MBR и были разбиты используя схему разбивки MBR. Вот как это все было и нам это нравилось!
Затем появились EFI и UEFI, встроенные программы нового образца наряду со схемой разбивки GPT, поддерживающая диски размером более 2.2TБ. Неожиданно, нам стали доступны различные способы установки и загрузки Линукс систем . То, что было единым методом, стало чем-то более сложным.
Воспользуемся моментом и рассмотрим доступные способы конфигурации жесткого диска для загрузки Funtoo Linux. Данное Руководство рекомендует способ "по-старинке" , загрузка BIOS и использование MBR. Данный способ работает (за исключением редких случаев) и всесторонне поддерживается. И в этом нет ничего плохого. Если Ваш жесткий диск 2TБ или меньшего размера это не является препятствием для использования всего дискового пространства.
Но, бывают ситуации когда метод "по-старинке" не является оптимальным. Если Ваш жесткий диск размером более 2TБ , MBR разбивка не сможет обеспечить доступ ко всему дисковому пространству. Это одна из причин. Вторая причина: существуют "PC" системы, которые более не поддерживают BIOS загрузку и форсируют UEFI загрузку. Из чувства сострадания к тем, кто попал в затруднение перед выбором, это Руководство также описывает установку и загрузку UEFI систем.
Мы всё же рекомендуем разбивку "по-старинке". Загрузчик, который мы используем для загрузки Линукс в этом руководстве называется GRUB, таки образом мы называем метод как BIOS + GRUB (MBR) . Это традиционный способ установки на PC-совместимые компьютеры.
Если Вам необходимо использование UEFI для загрузки, мы советуем не использовать MBR вообще, ввиду того, что некоторые системы поддерживают MBR, а некоторые нет. Вместо, мы советуем использование UEFI для загрузки GRUB, который, затем в свою очередь загрузит Линукс. Мы называем этот метод как UEFI + GRUB (GPT).
И да, есть еще несколько способов, некоторые из них задокументированы в Boot Methods . Обычно мы рекомендуем BIOS + GRUB (GPT) метод, но он ограничивается не столь широкой поддержкой со стороны комплектующих.
Вопрос -- какой из методов использовать? Вот какой.
- Принцип 1 - "По-старинке"
- Если Вы можете успешно загрузить System Rescue CD и видите синее меню, то Вы используете BIOS, и скорее всего Вы можете загрузить Funtoo Linux используя BIOS. Итак, следуйте этому способу и используйте BIOS загрузку, кроме случаев Вам по-какой либо причине необходим UEFI, например если размер жесткого диска >2.2TБ. В этом случае следуйте Принцип 2.
- Принцип 2 - "Модерн"
- Если Вы можете успешно загрузить System Rescue CD и видите черно-белое меню -- поздравления, Ваша система поддерживает UEFI загрузку. Это значит, что Вы готовы установить Funtoo Linux к загрузке с помощью UEFI. Ваша система также может поддерживать загрузку BIOS, но попрбуйте UEFI для начала. Вы можете "покопаться" в настройках BIOS.
- Какая разница между "По-старинке" и "Модерн"?
- Если Вы следуете MBR разбивке, Ваш
/boot
раздел будет отформатирован файловой системой ext2 , и Вы будете использовать fdisk
для создания MBR разделов. Если Вы следуете "модерн", GPT разделам и UEFI загрузке, Ваш /boot
раздел будет отформатирован в файловую систему vfat, поскольку это единственная файловая система поддерживаемая UEFI, и Вы будете использовать gdisk
для создания GPT разделов. И Вы установите GRUB несколько иначе. Вот к чему сводится различие между методами.
- Имейте в виду
- Для установки Funtoo Linux используя метод "модерн", Вы должны загрузить System Rescue CD в UEFI режиме -- и увидеть начальное черно-белое меню. В противном случае, UEFI не активно и Вы не сможете продолжить!
Note
Некоторые материнские платы якобы поддерживают UEFI, но на самом деле нет. Исследуйте . К примеру, Award BIOS в моей Gigabyte GA-990FXA-UD7 rev 1.1 имеет возможность включить UEFI загрузку для CD/DVD. Этого не достаточно для обеспечения UEFI загрузки для жестких дисков и установки Funtoo Linux. UEFI должно поддерживать и сьемные носители (таким образом Вы сможете загрузить System Rescue CD используя UEFI) и жесткие диски (Вы можете загрузить Funtoo Linux.) Оказывается, что более поздние ревизии этой платы (rev 3.0) имеют новую версию BIOS который полностью поддерживает UEFI. Это приводит к третьему принципу -- знайте Ваши комплектующие.
Метод (BIOS/MBR) "По-старинке"
Note
Используйте данный метод при загрузке с помощью BIOS, и если System Rescue CD имеет начальное меню загрузки светло-голубое. Если Вы собираетесь использовать "модерн", кликните здесь в меню UEFI/GPT.
Подготовка
Прежде чем начать , неплохо бы удостовериться, что Вы используете нужный диск для разбивки. Попробуйте эту комманду и проверьте, что /dev/sda
тот самый диск, который Вы желаете разбить:
root # fdisk -l /dev/sda
Disk /dev/sda: 640.1 GB, 640135028736 bytes, 1250263728 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 label type: gpt
root # Start End Size Type Name
1 2048 1250263694 596.2G Linux filesyste Linux filesystem
Теперь, рекомендуем стереть существующие таблицы разделов MBR или GPT, которые могут помешать BIOS во время загрузки. Мы используем комманду sgdisk
:
Warning
Это необратимый процесс, который уничтожит все разделы! Вы предупреждены! Советуем сохранить критические данние перед этим.
root # sgdisk --zap-all /dev/sda
Creating new GPT entries.
GPT data structures destroyed! You may now partition the disk using fdisk or
other utilities.
Не стоит беспокоится об этом сообщении, так как комманда успешно выполнена:
***************************************************************
Found invalid GPT and valid MBR; converting MBR to GPT format
in memory.
***************************************************************
Разбивка диска
Теперь мы используем fdisk
для создания таблицы разделов MBR и самих разделов:
root # fdisk /dev/sda
В консоли fdisk
, следуйте следующим шагам:
Очистить таблицу разделов:
Command (m for help): o ↵
Создать раздел 1 (boot):
Command (m for help): n ↵
Partition type (default p): ↵
Partition number (1-4, default 1): ↵
First sector: ↵
Last sector: +128M ↵
Создать раздел 2 (своп):
Command (m for help): n ↵
Partition type (default p): ↵
Partition number (2-4, default 2): ↵
First sector: ↵
Last sector: +2G ↵
Command (m for help): t ↵
Partition number (1,2, default 2): ↵
Hex code (type L to list all codes): 82 ↵
Создать корневой раздел:
Command (m for help): n ↵
Partition type (default p): ↵
Partition number (3,4, default 3): ↵
First sector: ↵
Last sector: ↵
Проверить таблицу разделов:
Command (m for help): p
Disk /dev/sda: 298.1 GiB, 320072933376 bytes, 625142448 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
Disklabel type: dos
Disk identifier: 0x82abc9a6
Device Boot Start End Blocks Id System
/dev/sda1 2048 264191 131072 83 Linux
/dev/sda2 264192 4458495 2097152 82 Linux swap / Solaris
/dev/sda3 4458496 625142447 310341976 83 Linux
Записать таблицу разделов на диск:
Command (m for help): w
Ваша новая таблица разделов будет записана на диск.
Метод (UEFI/GPT) "Модерн"
Note
Используйте данный метод при загрузке с помощью UEFI, и если System Rescue CD имеет начальное меню загрузки черно-белого цвета. Если оно было светло-голубого цвета, этот метод не будет работать.
Комманда gdisk используется для создания таблицы разделов GPT . Измените размеры в соответсвии Вашим требованиям, хотя приведенные ниже размеры будут работать для большинства пользователей. Запустите gdisk
:
root # gdisk
В консоли gdisk, следуйте следующим шагам:
Создайте новую пустую таблицу разделов (Это уничтожит данные при сохранении на диск):
Command: o ↵
This option deletes all partitions and creates a new protective MBR.
Proceed? (Y/N): y ↵
Создайте раздел 1 (загрузочный):
Command: n ↵
Partition Number: 1 ↵
First sector: ↵
Last sector: +500M ↵
Hex Code: ↵
Создайте раздел 2 (своп):
Command: n ↵
Partition Number: 2 ↵
First sector: ↵
Last sector: +4G ↵
Hex Code: 8200 ↵
Создайте раздел 3 (корневой):
Command: n ↵
Partition Number: 3 ↵
First sector: ↵
Last sector: ↵ (for rest of disk)
Hex Code: ↵
По пути Вы можете набрать "p" и нажать Enter для просмотра текущей таблицы разделов. Если Вы допустили ошибку, наберите "d" для удаления созданного раздела. Если Вы удовлетворены Вашей схемой разделов, наберите "w" для записи таблицы на диск:
Записать таблицу разделов на диск:
Command: w ↵
Do you want to proceed? (Y/N): Y ↵
Таблица разделов будет записана на диск и gdisk завершит работу.
Теперь GPT/GUID разделы созданы, и будут показаны как блочные утройства в Linux:
- /dev/sda1, будет использоваться для /boot, загрузочный раздел
- /dev/sda2, будет использоваться как своп , и
- /dev/sda3, корневой раздел.
Создание файловых систем
Note
Данная часть рассматривает как BIOS так и UEFI установки. Не пропускайте раздел!
Прежде чем Ваши только что созданные разделы могут быть использованы, блочные устройства должны быть инициализированы метаданными файловой системы. Данный процесс известен как создание файловой системы. После этого блочные устройства могут быть смонтированы и использоваться для хранения данных .
Будем проще. Используете разделы MBR, метод "по-старинке" ? Если да, давайте создадим файловую систему ext2 на /dev/sda1:
root # mkfs.ext2 /dev/sda1
Если Вы используете разделы GPT для UEFI, метод "модерн", Вам нужно создать файловую систему FAT32 на /dev/sda1, поскольку это единственная поддерживамая UEFI фаловая система:
root # mkfs.vfat -F 32 /dev/sda1
Теперь, создадим своп раздел. Он будет использоваться как дисковая виртуальная память для системы Funtoo Linux.
Вы не будете создавать никакой файловой системы на своп разделе, поскольку он не используется для хранения каких-либо данных. Но необходимо инициализировать своп коммандой mkswap
. Далее мы используем комманду swapon
для незамедлительной активации своп-раздела в окружении живого диска live CD, в случае необходимости доступа к своп во время установки:
root # mkswap /dev/sda2
root # swapon /dev/sda2
Теперь, нам необходимо создать корневую файловую систему. Здесь будет жить Ваш Funtoo Linux. Обычно мы рекоммендуем ext4 или XFS. Если Вы не уверены, выбиайте ext4. Вот как создать файловую систему ext4:
root # mkfs.ext4 /dev/sda3
...и вот как создать файловую систему XFS, если это Ваш выбор для корневой системы:
root # mkfs.xfs /dev/sda3
Your filesystems (and swap) have all now been initialized, so that that can be mounted (attached to your existing directory heirarchy) and used to store files. We are ready to begin installing Funtoo Linux on these brand-new filesystems.
Warning
When deploying an OpenVZ host, please use ext4 exclusively. The Parallels development team tests extensively with ext4, and modern versions of openvz-rhel6-stable
are not compatible with XFS, and you may experience kernel bugs.
Mounting filesystems
Mount the newly-created filesystems as follows, creating /mnt/funtoo
as the installation mount point:
root # mkdir /mnt/funtoo
root # mount /dev/sda3 /mnt/funtoo
root # mkdir /mnt/funtoo/boot
root # mount /dev/sda1 /mnt/funtoo/boot
Optionally, if you have a separate filesystem for /home
or anything else:
root # mkdir /mnt/funtoo/home
root # mount /dev/sda4 /mnt/funtoo/home
If you have /tmp
or /var/tmp
on a separate filesystem, be sure to change the permissions of the mount point to be globally-writeable after mounting, as follows:
root # chmod 1777 /mnt/funtoo/tmp