aboutsummaryrefslogtreecommitdiff
path: root/content/weblog/2018-12-31_intro-to-linux-and-bash-pt2
diff options
context:
space:
mode:
Diffstat (limited to 'content/weblog/2018-12-31_intro-to-linux-and-bash-pt2')
-rw-r--r--content/weblog/2018-12-31_intro-to-linux-and-bash-pt2/index.md398
-rw-r--r--content/weblog/2018-12-31_intro-to-linux-and-bash-pt2/index.ru.md404
2 files changed, 802 insertions, 0 deletions
diff --git a/content/weblog/2018-12-31_intro-to-linux-and-bash-pt2/index.md b/content/weblog/2018-12-31_intro-to-linux-and-bash-pt2/index.md
new file mode 100644
index 0000000..5739e06
--- /dev/null
+++ b/content/weblog/2018-12-31_intro-to-linux-and-bash-pt2/index.md
@@ -0,0 +1,398 @@
++++
+title = "Intro to Linux and the Bash command line, pt II"
+date = 2018-12-31T09:20:00Z
++++
+
+So the year is coming to an end, and I didn't follow up on the first part of
+these mini tutorial/guide/introduction. Might as well end the year on a good
+note and write at least one post this last month.
+
+<!-- more -->
+
+In this part I will be writing about some more aspects of Linux and Unix-like
+systems and tools that will come in handy when using the terminal. All or most
+of these tools are a standard part of Linux and Unix/Unix-like systems.
+
+## File manipulation
+
+I didn't get into detail in the previous part of this guide on the file
+manipulation side of things. However it is a crucial part of any computer
+system, after all they wouldn't be as useful as they are if you couldn't create,
+edit and delete files.
+
+### Create files
+
+Usually, the way you would go about creating and editing files is by using the
+corresponding programs. Like for example, vim to create and edit text files.
+However, there's also a utility to create blank files called touch.
+
+You can make a blank file by writing touch followed by the path of the file you
+wish to create, like this
+
+```sh
+user@host:~$ touch example.txt
+```
+
+Now we have an empty file at "/home/user/example.txt". Although I kind of lied
+when I said that this command is for making blank files. In reality, what it
+does is check if such file exists, if it does, it modifies the date and time of
+access and modification, otherwise it makes a new empty file, like in our case.
+Most of the time you won't really need this command, since you would actually be
+creating files through programs or means, though it does come in handy
+sometimes.
+
+### Create directories
+
+Now on to something more interesting, making directories. This one is quite
+simple, and the command for that is mkdir. For example
+
+```sh
+user@host:~$ mkdir foo
+```
+
+In this case we have created a new folder called "foo" in "/home/user/". But
+remember that we are passing paths here, which can be relative or absolute (if
+you don't know or remember what this means, check the first part of this guide).
+In our case we were using a relative path, with just the name of the directory
+to create.
+
+If we were to indicate an absolute path like "/home/user/foo" we would need to
+make sure that directories "home" and "user" already exist. However, there's a
+useful argument we can pass to mkdir to make parent directories if needed, -p
+
+```sh
+user@host:~$ mkdir -p /tmp/foo/bar
+```
+
+In this case, if directory "foo" doesn't exist, mkdir will make it for us along
+with "bar" inside it.
+
+### Moving and renaming
+
+This one is pretty simple, and both actions are handled by the same command, mv,
+which is short for move.
+
+If you want to rename a file or directory, simply "move" it to the same
+destination directory with a new/different name, for example
+
+```sh
+user@host:~$ mv untitled titled
+```
+
+If you want to move it to a different location, just indicate that path as the
+second argument. Remember that we are using paths here, and we use either
+absolute or relative paths
+
+```sh
+user@host:~$ mv titled Documents/titled
+```
+
+### Copying
+
+Copying files is similar to moving them, except that the command is different,
+cp
+
+```sh
+user@host:~$ cp titled Documents/titled2
+```
+
+However, copying directories is different. To copy directories you have to use a
+special flag, the -r flag. This flag means that the operation ought to be
+recursive, that is to copy every file and subdirectory in that directory along
+with the directory (and files in those subdirectories and files the
+subdirectories of the subdirectories and... yeah recursion, you get it) to the
+destination path. So we would do something like this
+
+```sh
+user@host:~$ cp -r dir dir-copy
+```
+
+### Removing
+
+Removing files is pretty simple, just use rm followed by the path of the file,
+for example
+
+```sh
+user@host:~$ rm title
+```
+
+However, removing directories is a little bit trickier. One option would be to
+use the command rmdir, however, the directory has to be empty before you can
+remove it.
+
+The second option, is to use the same command as we used with files, but passing
+it the -r flag so that it removes files recursively, similar to what we did with
+the copy (cp) command. Do watch out, as it will remove the directory along with
+everything that is in it.
+
+So to remove a directory and everything in it, we input something like this
+
+```sh
+user@host:~$ rm -r dir
+```
+
+This command also has another flag to forcefully remove files without prompting,
+the -f flag. This might be useful when you are removing files recursively and
+there might be some special files, like hidden files (the ones with a dot as the
+first character) and you don't want to be prompted for each and everyone of
+them.
+
+Thread REALLY carefully when using this command though, especially if you are
+issuing it as root. You don't wanna issue a "sudo rm -rf /" and end up with a
+borked system and lost files. Unless you are some kind of sadist or something.
+
+An example of when it might be useful, is when you need to delete a git
+repository from your computer, since it contains a lot of special hidden files
+which git uses to keep track of your commits and other stuff. So to remove it,
+we do
+
+```sh
+user@host:~$ rm -rf somerepo
+```
+
+### Permissions
+
+The Unix or Unix-like user and permissions systems, is a robust system for
+managing what particular users can do with certain files and directories. This
+allows to create a secure environment, especially when there are multiple users
+using one computer.
+
+Every file has three types of permissions which dictate what can be done with
+it. Each permission is represented by a single letter
+
+* r - read: the user can read/view the file.
+* w - write: the user can write/modify (this includes deleting) the file.
+* x - execute: the file can be run or executed by the user, if it is a program
+ or script.
+
+There are as well three different sets of people the permissions and ownership
+might apply to. These are
+
+* u - user/owner: the one user that owns the file. Usually it is the user that
+ created the file, but ownership can be modified.
+* g - group: every file has a group it belongs to. The group can be a one user
+ group (every user has their own one-user group), or a common group with
+ multiple users.
+* o - others: everybody else who is not either in the group or the owner.
+
+If you read the first part of this guide you might remember that I mentioned
+using the command "ls -l" to list the contents of the directory with details
+about the files, including permissions
+
+```sh
+user@host:~/Documents$ ls -l
+drwxr-xr-x 2 user user 4.0K Jul 18 04:20 Books
+-rwxr-xr-- 1 user group 350 Jul 18 04:20 run.py
+-rw-r--r-- 1 user user 1.2M Jul 18 04:20 picture.png
+```
+
+As mentioned in the first part, the first ten characters of a row of the output
+is what tells us about the permissions of the given file in that row.
+
+The first character in that sequence tells us if it is a normal file, or a
+directory. If it has a d, it is a directory (duh), if it has a dash, it is a
+normal file. It can be another letter, like an l for a symbolic link (a topic
+for another day).
+
+The next 9 characters are divided in subsequences of three letters, each for a
+set of people. The first three characters after the file type one are the
+permissions for the owner, the next three are for the group, and the last three
+for others.
+
+In each of this subset of three characters, the permissions are in the order of
+read, write, and execute. So a letter means that that said set of users have
+said permission, and its absence means the lack of that permission.
+
+Let's take for example the "run.py" file. By the information there we can see
+that it is a normal file (no d (that's what she said)), its owner (user) can
+read, write and even execute it; the group users (in group group) can read and
+execute it, but not write to it; and the others can just take a look at its
+contents.
+
+You might have noticed that directories tend to have the "x" part of the
+permissions, however, this means something a little bit different on directories
+than on files. It doesn't mean that you can execute but rather that you can
+"search it", or in other words, access files inside of it. Because having the
+"read" permission on a directory only means that you can take a look at what
+files are inside of it, and write that you can put files inside the directory.
+
+### Changing permissions
+
+There is a really useful command that allows us to change permissions on files,
+chmod. It is short for change file mode bits.
+
+To change the permissions on the file you input chmod followed by the
+permissions and the path of the file. There are two ways of setting the
+permissions, the easy and long one using letters, and the short but not as easy
+way with octal "permission bits". We'll take a look at the easy one first.
+
+The easier way is made up of three parts
+
+* Who - user/owner, group, others or all (u, g, o, or a)
+* Revoke or grant, "+" to grant, "-" to revoke
+* The permission we are setting - read, write or execute (r, w, or x)
+
+So let's suppose we have a script we want to set the execute permission for so
+that any user in the computer can execute it.
+
+```shh
+user@host:~/Documents/stuff$ ls -l
+-rw-r--r-- 1 user group 420 April 20 6:59 script.sh
+user@host:~/Documents/stuff$ chmod a+x script.sh
+-rwxr-xr-x 1 user group 420 April 20 6:59 script.sh
+```
+
+As we can see, after executing the command, every user on the computer now has
+execute permission on the script. Now let's say that we want to revoke read
+permissions for everybody except for the owner (user), we could execute o-r and
+then g-r, but we can also combine them, like so
+
+```sh
+user@host:~/Documents/stuff$ chmod go-r script.sh
+-rwx--x--x 1 user group 420 April 20 6:59 script.sh
+```
+
+Now onto the short way. This one's a bit harder to remember as you have to have
+some understanding of binary. Basically the way it works is that you set the
+permissions by passing three octal numbers (i.e., 0-7) that each represent the
+permission bits for each set of people (user/owner, group, others).
+
+As it is we have three possible permissions (read, write and execute) and 2^3
+just so happens to be 8 (possible combinations), that's why it is in octal.
+Here's a table to help you out
+
+
+<table>
+ <tbody>
+ <tr>
+ <td>Octal</td>
+ <td>Binary</td>
+ </tr>
+ <tr>
+ <td>0</td>
+ <td>001</td>
+ </tr>
+ <tr>
+ <td>1</td>
+ <td>001</td>
+ </tr>
+ <tr>
+ <td>2</td>
+ <td>010</td>
+ </tr>
+ <tr>
+ <td>3</td>
+ <td>011</td>
+ </tr>
+ <tr>
+ <td>4</td>
+ <td>100</td>
+ </tr>
+ <tr>
+ <td>5</td>
+ <td>101</td>
+ </tr>
+ <tr>
+ <td>6</td>
+ <td>110</td>
+ </tr>
+ <tr>
+ <td>7</td>
+ <td>111</td>
+ </tr>
+ </tbody>
+</table>
+
+Basically what this means, is that when we have a 1, said permission is granted,
+when it is 0, it is not. So for example, 6 means that read and write have been
+granted, but not execute, because 6 => 110 => rw-.
+
+So let's say for example that we want to set the permissions of file so that the
+owner can read, write, and execute, the group can read and execute, and others
+can only execute. It would look something like this
+
+```sh
+user@host:~/Documents/stuff$ chmod 751 script.sh
+user@host:~/Documents/stuff$ ls -l
+-rwxr-x--x 1 user group 420 April 20 6:59 script.sh
+```
+
+If you are changing the permissions of a directory, the permissions will apply
+only to the directory itself and not to the files and subdirectories inside of
+it, unless you use the recursive flag -R (note that in the case of chmod and
+chown it is a capital R).
+
+### Changing ownership
+
+Changing the owner of a file is easier than changing permissions, since less
+variables are involved. To change owner we use the chown command, for example,
+change the user that owns a file
+
+```sh
+user@host:~/.logs$ ls -l
+-rw-r--r-- 1 root root 69 April 20 6:59 some.log
+user@host:~/.logs$ sudo chown user some.log
+user@host:~/.logs$ ls -l
+-rw-r--r-- 1 user root 69 April 20 6:59 some.log
+```
+
+As the file doesn't belong to the same user initially, we need to use sudo
+elevate our permissions to "super user". Note that in order to be able to use
+sudo or "elevate your permissions" your user needs to be either in the sudoers
+file or in other distros in the "wheel" group, or both. I won't go into details
+on how to do that, since most probably your user is already in the sudoers file,
+and a quick search on the internet will give you the information needed.
+
+Now let's say that you wanted to change both the user and group that file
+belongs to, we would do like this
+
+```sh
+user@host:~/.logs$ ls -l
+-rw-r--r-- 1 root root 69 April 20 6:59 some.log
+user@host:~/.logs$ sudo chown user:group some.log
+user@host:~/.logs$ ls -l
+-rw-r--r-- 1 user group 69 April 20 6:59 some.log
+```
+
+Just as with chmod, if you want to change ownership recursively in a directory,
+you need to use the -R flag.
+
+## Epilogue/Some tips
+
+I forgot to mention in the previous part how to write paths with spaces. You
+cannot write paths with spaces just like that, since spaces are treated as the
+separator between arguments.
+
+There are two ways of writings paths and filenames (and other arguments) with
+spaces. One is to put the argument between quotation marks, like for example
+
+```sh
+user@host:~/Documents$ rm "Shopping List.txt"
+```
+
+Another is to use an escape character, i.e. just put a backslash (\) before the
+space, like this
+
+```sh
+user@host:~/Documents$ rm Shopping\ List.txt
+```
+
+One more thing that I wanted to mention is the man(ual) pages. Basically all
+Linux distros come with man pages.
+
+You don't always have to resort to the internet if you don't remember how to use
+a command, like what flags a command accepts, what are the order of the
+arguments, etc. You might not have internet one day, and you might to resort to
+good ol' offline resources, and the man pages are a good one.
+
+Besides, it is sometimes faster and easier to not have to leave the terminal to
+look up the information.
+
+To read the man(ual) pages of a command, input "man" followed by the name of the
+command, e.g. "chmod", and it will provide you with almost all the information
+that you need.
+
+You can use vim keys (hjkl), or the arrow keys to scroll. Type /<word> to search
+for that word, and afterwards press n to find the next found item.
+
+This is all for this part. Happy 2019!
diff --git a/content/weblog/2018-12-31_intro-to-linux-and-bash-pt2/index.ru.md b/content/weblog/2018-12-31_intro-to-linux-and-bash-pt2/index.ru.md
new file mode 100644
index 0000000..34ad9d9
--- /dev/null
+++ b/content/weblog/2018-12-31_intro-to-linux-and-bash-pt2/index.ru.md
@@ -0,0 +1,404 @@
++++
+title = "Intro to Linux and the Bash command line, pt II"
+date = 2018-12-31T09:20:00Z
++++
+
+И так, год подходит к концу, и я так еще не написал вторую часть туториала про
+Bash и Linux. Надо бы написать хотя бы один пост в этом, последнем месяце года.
+
+<!-- more -->
+
+В этой части, я расскажу чуть больше про инструменты и команды в Linux и
+Unix-подобных системах, которые вам пригодятся при работе в терминале. Все или
+большинство из этих программ являются частью основного набора программ и утилит
+большинства бистрибутивов Linux и Unix/Unix-подобных систем.
+
+## Работа с файлами
+
+В предыдущей части я стал объяснять подробно как работать с файлами. Однако,
+возможность манипулировать файлы является очень полезным и важным функционалом
+компьютерных систем.
+
+### Создать файл
+
+Обычно, если хотим создать файл, мы используем определенную программу специально
+предназначена для создания и редактирования определенного вида файлов. Например,
+vim для редактирования и записи текстовых файлов. Однако есть утилита которая
+позволяет создавать пустые файлы - touch.
+
+Вы можете создать пустой файл введя touch и последовательно название или путь
+файла который вы хотите создать, например
+
+```sh
+user@host:~$ touch example.txt
+```
+
+А теперь у нас пустой файл в "/home/user/example.txt". Но, я немного соврал,
+когда сказал что данная команда для того чтобы создавать пустые файлы. На самом
+деле, она сначала проверяет наличия файла, затем, если он существует, она
+редактировает его даты и время доступа и редактирования, иначе он создает пустой
+файл, как в данном случае. Очень редко когда данная команда на самом деле
+понадобится, поскольку в большинство случаях сами программы для редактирования
+файлов могут также их создавать. Тем не менее бывают случаи когда она может
+пригодится.
+
+### Создать директорий
+
+Сейчас у нас будет что-то поинтереснее, как создать директорий. Создавать
+директории довольно просто, команда - mkdir. Например
+
+```sh
+user@host:~$ mkdir foo
+```
+
+Мы только что создали директорий "foo" в "/home/user/". Не забудьте что мы
+всегда передаем путь файла, будь они относительными или абсолютными (если вы не
+помните что это значит, прочитайте первую часть). В данном случае, мы используем
+относительный путь содержающий только название директория.
+
+Если бы мы использовали абсолютный путь, он выглядел бы таким образом -
+"/home/user/foo". Нам бы пришлось убедиться в том что директории "home" и "user"
+существуют. Однако, существует очень подезный флажок, которые мы можем передать
+команде, чтобы она создавала родительские директории при необходимости - -p
+
+```sh
+user@host:~$ mkdir -p /tmp/foo/bar
+```
+
+Если директории "tmp" и/или "foo" не существуют, он их автоматический сделает,
+вместе с "bar" внутри их.
+
+### Перемещение и переименования
+
+Это довольно просто, и обе действия можно выполнить одной командой - mv, что
+происходит с английского move.
+
+Если вам необходимо переименовать файл или директорий, переместите его в тот же
+самый директорий, с новым/другим названием, например
+
+```sh
+user@host:~$ mv untitled titled
+```
+
+А вот если потребуется переместить в другую локацию, просто укажите путь новой
+локации в качестве второго аргумента. Не забудьте что оба аргумента являются
+путями, либо относительными либо абсолютными
+
+```sh
+user@host:~$ mv titled Documents/titled
+```
+
+### Копировать
+
+Копирование похоже на перемещения, отличие просто в названии команды - cp.
+
+```sh
+user@host:~$ cp titled Documents/titled2
+```
+
+Однако, копирование директории отличается немного от копирования файлов. Чтобы
+копировать директории, нужно использовать флаг -r. Он указывает что операция
+должна быть рекурсивной, то есть, нужно скопировать каждый файл и поддиректорию
+внутри директории (и файлы внутри этих поддиректории и в поддиректории
+поддиректории и... ну то есть, рекурсия) в указанный путь. То есть что-то похоже
+на это
+
+```sh
+user@host:~$ cp -r dir dir-copy
+```
+
+### Удалить
+
+Удалять файлы довольно просто, достаточно ввести rm а затем путь файла
+
+```sh
+user@host:~$ rm title
+```
+
+Однако, чтобы удалять директории не так просто. Один способ - использовать
+команду rmdir, но она только работает на пустых директориях.
+
+Второй вариант, использовать ту же команду что и для файлов, но используя флаг
+-r чтобы удалить файлы рекурсивно, также как и с командой cp. Будьте
+внимательные при использовании этой команды, ибо она удаляет все файлы внутри
+директории, вместе с директорией.
+
+Итак, чтобы удалить директорию и все содержимое, нам понадобиться ввести
+следующую команду
+
+```sh
+user@host:~$ rm -r dir
+```
+
+У этой команды есть еще один флаг, чтобы принудительно удалить файлы без
+вопросов - флаг -f. Этот аргумент может пригодится, например, когда нужно
+удалить сразу несколько файлов, и среди них есть специльные файлы, как скрытые
+файлы (те, у которых точка перед названием) и вам не хочется подтвердить
+действие перед каждым файлом.
+
+Следует быть ОЧЕНЬ осторожным перед тем как использовать этот флаг, особенно
+если вы собираетесь ввести команду под root пользователем. Поверьте, вам будет
+очень неприятно если вы введете например "sudo rm -rf /" и у вас полетят
+полностью система и файлы. Если вы не садист, конечно.
+
+Пример ситуации когда данное сочетание флагов с командой rm может пригодится
+это, когда вам необходимо удалить репозиторий git, поскольку в них содержатся
+множество специальных скрытых файлов, которые git использует затем чтобы следить
+за коммитами и прочее. Пример использования команды
+
+```sh
+user@host:~$ rm -rf somerepo
+```
+
+### Контроль доступа
+
+В Unix и Unix-подобных системах существует довольно прочная система для контроля
+прав доступа. Она позволяет определять полномочия определеных пользователей или
+групп пользователей над определенными файлам, создавая безопасную среду для
+компьютеров с множество пользователями.
+
+У каждого файла три вида прав доступа, которые определяют что можно с ними
+делать. Каждое право обозначается одной буквой английского алфавита
+
+* r - чтение: пользователь имеет право читать данный файл.
+* w - запись: пользователь может писать/редактровать данный файл (включая
+ возможность его удалять).
+* x - выполнение: файл может быть выполнен пользователем, если он является
+ программой или скриптом.
+
+Так же существует три разных наборов человек к которым могут относится права
+доступа
+
+* u - пользователь/владелец: пользователь, которому принадлежит файл. Обычно это
+ тот же самый пользователь, который создал файл, но владелца можно поменять.
+* g - группа: каждый принадлежит определенной группе пользователей. Это может
+ быть группа одного пользователя (у каждого пользователя есть своя
+ однопользовательская группа), или общая группа.
+* o - другие: Все остальные кто не являются владелцем или ну состоит в группе.
+
+Если вы читали первую часть туториала, вы наверное помните что я рассказывал про
+команду "ls -l" чтобы посмотреть дополнительную информацию о файлах, включая
+права доступа
+
+```sh
+user@host:~/Documents$ ls -l
+drwxr-xr-x 2 user user 4.0K Jul 18 04:20 Books
+-rwxr-xr-- 1 user group 350 Jul 18 04:20 run.py
+-rw-r--r-- 1 user user 1.2M Jul 18 04:20 picture.png
+```
+
+Первые десять символов в каждой строке - права доступа для файла в данной
+строке.
+
+Первый символ в данном сочетаний символов определяет является ли файл обычным
+файлом или другим видом. Если первым символом является буква d, то это
+директория, если там просто черточка (тире/дефис), то это обычный файл. Там
+также может быть другая буква, как например l для ссылок, но это уже не входит в
+рамках данного поста.
+
+Следующие 9 символов разделяются в свое время в сочетание из трех символов,
+каждое для определенного набора пользователей. Первые три символа после символа
+вида файла это права для владелца, следующие три для группы, и последние три для
+отсальных.
+
+В каждом из этих сочетании из трех букв, права доступа в порядке чтение, запись,
+выполнение. Наличие буквы означает что у данного набора пользвателей данно это
+право, отсуствие значит нет такого права для данного набора пользоваетелей.
+
+Возьмем в качестве примера файл "run.py". Исходя из информации на экране мы
+можем определить что это обычный файл (нет буквы d), владелец (user) имеет право
+читать, записывать и выполнять его; группа пользователей (в группе group) имеет
+право на чтение и выполнения, но не записи; и остальные только могут его читать.
+
+Наверное вы заметили что почти всегда у директории присуствует право на
+выполнение (буква x), однако это означает что-то немножко иное в отличие от
+файлов. Буква "x" у директориях означает что есть право на вход в директорию и
+есть доступ к файлам внутри директории. Право на чтения директории всего лишь
+означает что можно смотреть на то какие файлы содержатся в директории, и право
+на запись означает что есть то чтобы записывать файла внутри директории.
+
+### Изменить права
+
+Существует очень полезная команда которая позволяет менять права на доступ
+файлов - chmod.
+
+Чтобы изменить права на файле, необходимо ввести chmod и затем права и путь
+файла. Есть два способа чтобы менять права, легкий но более долгий способ
+используя буквы, и более быстрый но не совсем легкий используя восмеричный код.
+Начнем с более легкого.
+
+Более легкий способ состоит из трех частей
+
+* Кто - пользователь/владелец, группа, остальные или все (u, g, o, или a)
+* Дать или отменить право, "+" чтобы дать, "-" чтобы отменить
+* Право которое мы меняем - чтение, запись или испольнение (r, w, или x)
+
+Допустим у нас есть скрипт для которого мы хотим дать право на запуск для всех
+пользователей.
+
+```sh
+user@host:~/Documents/stuff$ ls -l
+-rw-r--r-- 1 user group 420 April 20 6:59 script.sh
+user@host:~/Documents/stuff$ chmod a+x script.sh
+-rwxr-xr-x 1 user group 420 April 20 6:59 script.sh
+```
+
+Как можно заметить, после запуска команды все пользователи компьютера имеют
+право на выполнения скрипта. А теперь допустим что мы передумали и хотим
+отменить право выполнения для всех пользователей кроме владелца, мы могли бы
+ввести o-r и затем g-r, но мы можем также совмещать следующим образом
+
+```sh
+user@host:~/Documents/stuff$ chmod go-r script.sh
+-rwx--x--x 1 user group 420 April 20 6:59 script.sh
+```
+
+А теперь пора выучить быстрый способ. Его сложнее запомнить, поскольку еще
+нужны базовые понимания двоичной системы счисления. Грубо говоря, оно работает
+подовая три цифры в восьмеричной системе счисления (то есть 0-7) каждая из
+которых обозначает бит права для каждого набора пользователей
+(пользователь/владелец, группа, другие).
+
+Получается у нас три возможные права (чтение, запись и выполнение) и 2^3 нам
+дает 8 возможных сочетании прав, и вот почему у нас восьмеричная система.
+Следующая таблица поможет определить отношение нужной цифры для определенного
+сочетания прав
+
+<table>
+ <tbody>
+ <tr>
+ <td>Восьмеричная система</td>
+ <td>Двоичная система</td>
+ </tr>
+ <tr>
+ <td>0</td>
+ <td>001</td>
+ </tr>
+ <tr>
+ <td>1</td>
+ <td>001</td>
+ </tr>
+ <tr>
+ <td>2</td>
+ <td>010</td>
+ </tr>
+ <tr>
+ <td>3</td>
+ <td>011</td>
+ </tr>
+ <tr>
+ <td>4</td>
+ <td>100</td>
+ </tr>
+ <tr>
+ <td>5</td>
+ <td>101</td>
+ </tr>
+ <tr>
+ <td>6</td>
+ <td>110</td>
+ </tr>
+ <tr>
+ <td>7</td>
+ <td>111</td>
+ </tr>
+ </tbody>
+</table>
+
+Зная как переводятся цифры в двоичную становится намного проще знать к какой
+комбинации прав она относится, ибо каждая цифра в сочетании трех бинарных цифр
+относится к одному виду прав в выше указанному порядке (r, w, x). Если у нас
+единица (1) это означает что есть данное право, а ноль (0) означает его
+отсуствие. И так, например, 6 означает что у нас есть право на чтение и запись,
+поскольку 6 = 110 = rw-.
+
+Допустим что мы хотим поменять права доступа к файлу таким образом чтобы
+владелец мог читать, записывать и выполнять; группа имела право на чтения и
+выполнения; и остальные могли только выполнять. Для этого мы ввели что-то
+подобное
+
+```sh
+user@host:~/Documents/stuff$ chmod 751 script.sh
+user@host:~/Documents/stuff$ ls -l
+-rwxr-x--x 1 user group 420 April 20 6:59 script.sh
+```
+
+Если вы меняете права доступа директория, новые права будут изменены только для
+самой директории, не включая файлы и поддиректории внутри. Чтобы также изменить
+права для всех файлов внутри директории, необходимо использовать флаг рекурсии -
+-R (обратите внимания на то что, в chmod флаг рекурсии обозначается большой
+буквой R в отличие от cp или rm).
+
+### Поменять владелца
+
+Менять владельца файла проще чем менять права. Чтобы поменять владельца необходимо
+использовать команду chown. Например, допустим мы хотим поменять пользователя,
+которого владеет файлом
+
+```sh
+user@host:~/.logs$ ls -l
+-rw-r--r-- 1 root root 69 April 20 6:59 some.log
+user@host:~/.logs$ sudo chown user some.log
+user@host:~/.logs$ ls -l
+-rw-r--r-- 1 user root 69 April 20 6:59 some.log
+```
+
+Поскольку файл не принадлежал тому же самому владельцу с которого мы выполняем
+команды, нам необходимо выполнить команду через sudo чтобы повысить наши
+права. Чтобы иметь возможность повышать права вашего пользователя, необходимо
+чтобы ваш пользователь состоял в файле "sudoers" и/или в группе "wheel" зависимо
+от дистрибутива/ОС. В большинство случаев (если вы пользуетесь
+"домашним/дестктопным" дистро) у вас уже будут права на sudo, в любом случае
+быстрый поиск в интернете поможет вам найти информацию о том как поменять
+настройки прав в вашем дистрибутиве/ОС.
+
+А теперь допустим что вы хотели поменять и пользователя и группу которому
+принадлежит файл, в таком случае мы бы ввели следующее
+
+```sh
+user@host:~/.logs$ ls -l
+-rw-r--r-- 1 root root 69 April 20 6:59 some.log
+user@host:~/.logs$ sudo chown user:group some.log
+user@host:~/.logs$ ls -l
+-rw-r--r-- 1 user group 69 April 20 6:59 some.log
+```
+
+Также как и с chmod, если вам необходимо поменять владелца рекурсивной в
+директории, вам нужно использовать флаг -R.
+
+## Эпилог/Советы
+
+В предыдущей части я забыл написать о том как ввести пути с пробедами. Нельзя
+просто так печатать пути с пробелами, ибо пробел означает переход к следующему
+аргументу.
+
+Есть два способа печатать пути, названия файлов и другие аргументы с пробелами.
+Первый способ - кавычки. Например
+
+```sh
+user@host:~/Documents$ rm "Shopping List.txt"
+```
+
+Второй - экранирования символа с помощью символа "\" перед пробелом. Например
+
+```sh
+user@host:~/Documents$ rm Shopping\ List.txt
+```
+
+Еще одно о чем я хотел рассказать - мануалы (man). Почти (если не все)
+дистрибутивы Линукса имеют мануалы.
+
+Не всегда необходимо обращаться к интернету если вы забыли как пользоваться
+определнной командой. Если вы однажды оказались без интернета и вы хотите
+узнать побольше об одной команде, man отличный оффлайн ресурс.
+
+Не говоря уже о том что проще и быстрее делать все сразу с терминала не
+переключаясь к браузеру чтобы искать нужную информацию.
+
+Чтобы прочитать мануал определенной команды, введите man и затем название
+команды. Например "man chmod".
+
+Вы можете пользоваться клавишами vim (hjkl) для перемещения. Введите /<термин>
+чтобы искать этот термин, а затем нажмите на n чтобы найти следующее совпадение.
+
+Это все на данный момент. С новым 2019-м годом!