From 65dfb21ce4bfd6c9b3d1628adeee0acfc423b2b5 Mon Sep 17 00:00:00 2001 From: Yaroslav Date: Sun, 12 Apr 2020 03:44:50 +0300 Subject: migrated all posts from 2018 --- .../2018-11-05_intro-to-linux-and-bash/index.md | 299 +++++++++++++++++++++ .../2018-11-05_intro-to-linux-and-bash/index.ru.md | 271 +++++++++++++++++++ 2 files changed, 570 insertions(+) create mode 100644 content/weblog/2018-11-05_intro-to-linux-and-bash/index.md create mode 100644 content/weblog/2018-11-05_intro-to-linux-and-bash/index.ru.md (limited to 'content/weblog/2018-11-05_intro-to-linux-and-bash') diff --git a/content/weblog/2018-11-05_intro-to-linux-and-bash/index.md b/content/weblog/2018-11-05_intro-to-linux-and-bash/index.md new file mode 100644 index 0000000..28db692 --- /dev/null +++ b/content/weblog/2018-11-05_intro-to-linux-and-bash/index.md @@ -0,0 +1,299 @@ ++++ +title = "Intro to Linux and the Bash command line" +date = 2018-11-05T23:53:00Z ++++ + +Recently I decided to introduce a friend of mine to the wonderful world of +Linux, and like when someone moves to a completely new town, you have to help +that friend get around town and learn about how things work in this new town, +where are all the places of interest, etc. And so it is, in someway, when +someone decides to make the move to a new OS, they have to get used to the new +environment and make new habits, especially regarding Linux. Therefore, I +decided to write this tutorial for my friend, and anybody who decided to try +Linux, and want to learn to use more effectively, that is, with a higher level +of skill than an average user. + + + +Most probably you already know, but Linux is not actually the OS itself, but +rather the kernel that is used in conjuction with a collection of programs and +packages called GNU (insert here jokes and memes about GNU/Linux (or +GNU+Linux)), and there are many different distributions (over 9000) of said +GNU/Linux. + +If you're just about to install Linux, and haven't decided yet on a distro, here +I wrote a small list of distros that might start with: + +* Manjaro - I personally use this distro. This one has different releases, with + different Desktop Environments (or DEs), like KDE or GNOME. This is a "rolling + release", what that means, is that instead of the classical update to version + x.x of the OS system, updates for each package are being rolled out + constantly, and sepparatly for each package. That is, you get basically the + latest packages, with the latest updates, at the cost of maybe some stability. + It is quite easy to get installed, and get started with (If you choose an + official release like Manjaro KDE or Manjaro GNOME). +* Ubuntu - The most know Linux distribution. It is one of the most + "user-friendly" distros out there. It is more stable than Manjaro (although + not always, unless you're using the Long-Term Support versions). If you just + want to install an OS where everything just works, and is already configured + for you, and you don't want to choose from a list of DEs (or you don't know + what a Desktop Environment is), this will most probably suit your needs. +* Debian - One the most stable distributions. It is not as easy to install as + Ubuntu or Manjaro due to large ammount of choice given during installation, + but it's not really hard to either. Actually, Ubuntu is derived from Debian. + You must probably will have to configure it to your needs and likings + (personally, I dislike the default settings of GNOME), but if you want real + stability, and distro that has been around almost as long as the kernel + itself, then this might be the distro for you. One downside of Debian, is that + because of its focus on stability, many packages on the main (stable) + branch/version are quite old/outdated. Another con of Debian, is that it + doesn't include "non-free" packages in the main repository (that is, there are + no proprietary packages by default), so if need a proprietary program or + package, like nvidia's drivers, you will have to add the corresponding + repositories by yourself. +* Fedora - It is similar to Ubuntu regarding stability and ease of use (i.e. + quite simple to use). I can't say much about Fedora, because I haven't used it + that much myself, but it is a very popular distribution. It has the same con + as Debian, in that it doesn't include "non-free" software in its main + repository. + +If you found "Desktop Environment" to be a unfamiliar term, in a nutshell, it is +the collection of programs and packages that present with the Graphical User +Interface for interaction with the system. How your OS/distribution is going to +look like doesn't depend as much on the distro itself, as on the DE that you +choose to install or comes with the distro. + +Do you have Linux installed? Excellent, now we can get started. + +## File structure + +If you are used to working with Windows systems, the the first thing that you +might notice is the difference in how files are handled/organized. In Windows, +because of its DOS legacy, drive letters are used to represent different drives, +partitions and file systems. In Linux, like in other Unix-like systems (e.g. +macOS, BSD) this differs somewhat. + +In Linux, everything is a file, including the devices that are connected to your +computer. From your keyboard (which is a read-only file) to your drives. +Directories are also files. + +Different disks or drives are mounted in a specific directory, and from this +directory, every file from that drive will be accessible. You can mount and +unmount drives yourself, but if you installed a distro with any of the most +popular desktop environments, then there's nothing to worry about, the system is +going to take care of mounting your pendrive for you, and creating a shortcut in +your file explorer and/or desktop each time you insert it. + +Linux has what is called a "root" directory + +``` +/ +``` + +In there are the files and subdirectories in your system are located, including +drives mounted in a specific subdirectory as mentioned before. + +Each user in Linux has its own "home" directory. Inside your home directory your +personal documents/files and subdirectories are going to be stored. All the home +directories of each user are usually going to be stored inside the "/home/" +directory. For example, for user "user", their home directory is going to be + +``` +/home/user +``` + +However, you can also move to your home directory by using the symbol ~. For +example, in your terminal, if you input + +```sh +$ cd ~ +``` + +You are going to be taken to your home directory (e.g. "/home/user/"). + +## The command-line - Bash + +Arguably the most useful program in Linux and any *nix system is the terminal. +Yes, maybe the average user won't have to use it, but it is the most flexible, +effective and useful instrument in your computer. A lot of work can be done +faster and more effectively in the terminal, rather than in a GUI. Obviously, it +is faster to learn to use a graphical interface, than a text-based or +command-line one, however, once you learn to properly use the terminal, you will +be able to use computer more efficiently than ever. + +Your command-line, if you haven't changed any defaults, will most probably look +something like this + +```sh +user@host:~$ +``` + +The first part before the "@" symbol, is the user with whom you have logged in. +After the "@" symbol is the "hostname" of your machine, i.e. the name of your +computer in a network. + +After the semicolon ":", the directory in which you are currently located is +going to be displayed. In our case, the "~" symbol is displayed, meaning that we +are inside our home directory. If you wish to see the full absolute path in +which you are located, you can input the command "pwd" + +```sh +user@host:~$ pwd +/home/user +user@host:~$ +``` + +The dollar "$" symbol, tells us that we are logged in as "normal" user. In Linux +and all *nix systems, there is a so called "super user", or just the "root" user +for short. Normal users don't have full access to all of the files in the +system, including other users' files. The root user has full access to all +system files. When you are logged in as the root user, the dollar "$" symbol is +going to be replaced by the hash "#" symbol. + +However, we will be talking about the root user and permissions another time. + +I can't tell you exactly how to open the terminal, as it is different in each +distro and desktop environment. You will have to look for the link that says +"Terminal" in your programs' menu, with the icon of a terminal on it. + +To be able to start working in the terminal, we'll need to become acquainted +with some of the main commands used for navigating. + +### Navigation in the terminal + +There is one more thing that needs to be taken into consideration when working +with Linux and Unix-like systems, and that is, case-sensitivity. *nix systems +are case-sensitive, in contrast to Windows ones, which aren't. What that means, +is that, if on Windows, files "README.TXT" and "readme.txt" are the same file, +in Linux and Unix they are completely different files. + +To move around directories, we use the "cd" (or change directory) command, +followed by the name, or path of the directory. The directory can be absolute or +relative. + +A relative path, is, for example, the name of a subdirectory inside the +directory in which we are currently located. In other words, the path relative +to where we are located. + +An absolute path, is the path relative to the root directory. + +For example, if we want to move to the "Documents" directory inside +"/home/user/", and we are already at "/home/user/", the we can just type the +following + +```sh +user@host:~$ cd Documents +user@host:~/Documents$ +``` + +If we wanted to move to that same directory from another location in the system, +we would type + +```sh +user@host:/var$ cd /home/user/Documents +user@host:~/Documents$ +``` + +To move one folder up, we write "..". Example + +```sh +user@host:~/Documents$ cd .. +user@host:~$ +``` + +The two dots "..", means the root directory of the current subdirectory. One dot +"." means the current directory. + +There is one more command, that will aid you in navigating - ls. This command +outputs a list of files and directories in the current location + +```sh +user@host:~/Documents$ ls +Books todo.txt picture.png +``` + +This command also accepts arguments and flags. For example, to list hidden files +as well, add the "-a" flag + +```sh +user@host:~/Documents$ ls -a +Books .secret todo.txt picture.png +``` + +Hidden files in Linux start with a dot (e.g., hidden directory ".secret"). + +There is also the "-l" parameter, which shows us a list of the contents with +additional information, such as, permissions (more on that in the next part), +amount of files inside a directory, owner of the file (user and group), size on +disk, datetime of creation/modification, and the name of the file. Example + +```sh +user@host:~/Documents$ ls -l +drwxr-xr-x 2 user user 4.0K Jul 18 04:20 Books +-rw-r--r-- 1 user user 350 Jul 18 04:20 todo.txt +-rw-r--r-- 1 user user 1.2M Jul 18 04:20 picture.png +``` + +You can mix flags as well, + +```sh +user@host:~/Documents$ ls -al +drwxr-xr-x 2 user user 4.0K Jul 18 04:20 Books +drwxr-xr-x 5 user user 4.0K Jul 18 04:20 .secret +-rw-r--r-- 1 user user 350 Jul 18 04:20 todo.txt +-rw-r--r-- 1 user user 1.2M Jul 18 04:20 picture.png +``` + +You can also take a look at what is inside a directory without having to move to +it first, by passing along as the last argument the name/path of said directory, +for example + +```sh +user@host:~/Documents$ ls -l Books +drwxr-xr-x 12 user user 4.0K Jul 18 04:20 Lessons +-rw-r--r-- 1 user user 2.3M Jul 18 04:20 Crime and Punishment.pdf +``` + +### Shortcuts + +Before we conclude the first part of this tutorial, I would like to mention some +useful "shortcuts" in bash. + +The first one is command history. Each time you input a command into the +terminal, it saves it in a history file. You can move around your command +history by using the up and down arrows. Let's say you want to repeat the last +command you used, instead of typing it all over again, you could just hit the up +arrow one time, maybe modify it a bit, and then press enter to input it. If you +want to use an older command, you can press the up arrow multiple times, and if +you missed the command you needed, you can go forward in your history by +pressing the down arrow. + +There is one more useful thing in Bash - Tab completion. When you press the +"Tab" key, bash will try to autocomplete the command for you. + +Let's say, for example, that you are in the root directory and you want to move +to "/home/user/". you can start typing "cd h", then press "Tab", so you now have +"cd home/", now type "u", press "Tab" one more time, and now you have "cd +home/user/". + +If there are multiple possible options to be autocompleted, then on the first +hit of the "Tab" key you are not going to get anything. If you don't get +anything it could also mean that there are nothing to autocomplete. In the first +case, if you press "Tab" twice, bash is going to output a list of possibilities, +for example + +```sh +user@host:~$ cd Do +Documents/ Downloads/ +user@host:~$ cd Do +``` + +In this case, we can type the next letter, for example "cd Doc", and press "Tab" +one more time, and we are going to get "cd Documents/". However, if you didn't +get anything on pressing "Tab" twice, it means that is nothing to autocomplete. + +It can be a little be hard to understand at first how "Tab completion" works, +but the best way to understand it, by trying it yourself. + +That is all for now, in the next part I am going to talk more about working on +the terminal. diff --git a/content/weblog/2018-11-05_intro-to-linux-and-bash/index.ru.md b/content/weblog/2018-11-05_intro-to-linux-and-bash/index.ru.md new file mode 100644 index 0000000..e9ba17d --- /dev/null +++ b/content/weblog/2018-11-05_intro-to-linux-and-bash/index.ru.md @@ -0,0 +1,271 @@ ++++ +title = "Intro to Linux and the Bash command line" +date = 2018-11-05T23:53:00Z ++++ + +Недавно я решил познакомить друга с великолепным миром Линукса, и как например, +человек переезжает в совсем новый город, его нужно познакомить с городом, как +передвигаться по городу, где все нужные заведения и т.д. В принципе и также +когда человек переходит на новую ОС, ему нужно привыкнуть к новой среде, +создавать новые привычки, особенно когда это касается мира линукса. Собственно +этот туториал я пишу для моего друга и любого другого человека который +заинтересован Линуксом, но хотят научится использовать его более эффективно, +т.е. высше уровня рядового пользователя. + + + +Скорее всего вам уже известно, но Линукс на самом деле сам по себе не ОС, а ядро +которое используется совместно с набором комонентов и программ GNU (вставьте +здесь шутки и мемы про GNU/Linux (или GNU+Linux)), и есть несколько вариантов, +или точнее - дистрибутивов, так называемого GNU/Linux. + +Если только собираетесь установить Линукс и еще не решились какой дистрибутив +выбрать, здесь маленткий, который может помочь вам выбрать: + +* Manjaro - Лично я пользуюсь этим дистрибутивом. У него есть несколько вариации + с разными рабочими средами, например KDE или GNOME. Это дистрибутив "rolling + release", что означает то, что у него будет более новые пакеты чем у + классических дистро, в замен меньшей стабильности системы. Его довольно легко + установить и использовать (если выбрать что-то вроде KDE или GNOME). +* Ubuntu - Самый известный дистрибутив. Является один из самых легких в + использовании. Более стабильный чем Manjaro (хоть и не всегда). Если вы просто + хотите установить ОС в которой уже все настроена и не хотите выбирать рабочую + среду (или вы не знаете что такое рабочая среда), скорее всего этот дистро для + вас. +* Debian - Один из самых стабильных дистро. Его не так легко установить как + Ubuntu или Manjaro, но все же не сложно. Собственно Ubuntu разработан на + основе Debian'а. Его скорее всего придется настроить под себя (лично меня не + нравятся дефолтные настройки GNOME'а), но если вы хотите стабильный, + провереный дистрибутив, то он для вас. Один минус для некоторых - поумолчанию + не подключены репозитории с "несвободным" софтом, придется подключить самому + если нуждаетесь в проприетарном софте. +* Fedora - По стабильностью и сложности установки/пользования похож на Ubuntu + (то есть довольный просто). У него такой же минус как и у Debian - отсуствия + "несвобоного" софта в главном репозиторий. + +Если при чтения списка вам словосочетание "рабочая среда" оказалась незнакомой, +то грубо говоря, это набор программ которые предоставляют вам графический +интерфейс для взаимодейстмия с системой. Как выглядит ОС не так сильно зависит +от дистро, в основном оно зависит от рабочей среды. + +Установили Линукс? Отлично, можем начать. + +## Файловая структура + +Если вы привыкли работать с Windows, то есть некоторые моменты, то первое что вы +заметите это то, что файловая структура выглядит немного иначе. Windows, из-за +наследства MS-DOS, использует буквы для обозначения дисков, томов и файловых +систем. В Линукс, как и в других Unix-подобных системах (например macOS, BSD) +это немного иначе. + +В Линуксе всё являтся файлом, в том числе и устройства подключенных к вашему +компьютеру. От клавиатуры до накопителя. Папки (или директории) тоже файлы. + +Разные диски или накопители монтируются в определеной папке, и в этой папке +будут размещатся файлы данного накопителя. Монтировать и демонтировать диски, +флэшки и тд можно самому, но нечего боятся, если вы установили какой-нибудь из +самых популярных дистро, то система сделать это для вас автоматический, и +создаст ярлык в браузере файлов или на рабочем столе. + +В Линуксе есть корневая папка + +``` +/ +``` + +Внутри нее все файлы и поддиректории вашей системы. + +В Линуксе, у каждого пользователя есть своя "домашняя папка". В вашей домашней +папки будут размещаться ваши файлы, документы. Домашняя папка пользователя +"user", например, будет распологатся здесь + +``` +/home/user +``` + +Но вы можете перейти к этой папке используя символ ~. Например, если в консоле +вы введете + +```sh +$ cd ~ +``` + +То это комманда вас переместит в вашую домашнюю папку (например, /home/user). + +## Терминал - Bash + +Самая полезная программа в линуксе, это скорее всего терминал. Да, рядовой +пользователь может и без нее жить, но это довольно гибкий и полезный инструмент. +Очень часто задачу на самом деле проще и быстрее реализовать в текстовой среде +чем в графической. Очевидно быстрее научится пользоватся графической средой, но +после того как вы научитесь пользоватся текстовой средой (терминал), вы сможете +работать более эффективно. + +Пример того как может выглядить ваша коммандная строка + +```sh +user@host:~$ +``` + +Первая часть - пользователь через которого вы зашли в систему. Вторая после +символа "@" - hostname, или название вашего устройства в сети. + +Вслед за ":" - директория в котором вы находитесь в данный момент. В этом случае +символ "~" указывает что мы находемся в домашнем каталоге нашего пользователя. +Чтобы посмотреть абсолютный путь, мы можем ввести комманду "pwd". + +```sh +user@host:~$ pwd +/home/user +user@host:~$ +``` + +Символ "$" указывает на то что мы сейчас работаем через обычного пользователя. В +Линуксе и во всех *nix системах, есть такая вещь как "супер пользователь", или +root пользователь. У обычных пользователей нет полный доступ к важным файлам +системы, или к файлам других пользователей. У root, доступ есть на всю систему. +Когда вы авторизованные через root, символ "$" меняется на "#". + +Но о правах и о root пользователе, попозже поговорим. + +Чтобы открыть терминал, достаточно зайти в меню программ/приложений и нажать на +его иконку или названия. Не могу объяснить подробнее где располагается ярлык +терминала, поскольку оно будет отличатся в зависимо от дистрибутива. + +Для того, чтобы начать работать в терминале, необходимо познакомится с основными +коммандами, начиная с коммандами для навигации. + +### Навигация в терминале + +Еще один момент, который стоит учесть при работе с Линуксом и *nix системами, +это то, что реестр учитывается. Если в Windows'е файл README.TXT и readme.txt +один и то же самый, то в Линуксе и Unix-подобных системах это разные файлы. + +Для перемещения по директориям, мы пришем в коммандой строке "cd <путь>". Путь +может быть относительным или абсолютным. + +Относительный путь, это, например, название папки которая находится внутри той +директории где мы находимся. Или иными словами, путь относительно того где мы +находимся. + +Абсолютный путь, это путь относительно корневой директории (или root на английском). + +Например, если мы хотим переместится в каталог "Documents" внутри /home/user/, и +мы уже в /home/user/, то мы можем просто ввести + +```sh +user@host:~$ cd Documents +user@host:~/Documents$ +``` + +А если бы нам надо было перейти на эту же папку с совершено другого каталога, то +нам бы пришлось ввести + +```sh +user@host:/var$ cd /home/user/Documents +user@host:~/Documents$ +``` + +Чтобы перейти на корневого каталога данной директории мы используем две точки +"..". Например + +```sh +user@host:~/Documents$ cd .. +user@host:~$ +``` + +".." означает корневой каталог данной директории. А также есть "." который +означает данная директория. + +Есть еще одна комманда, которая поможет вам при навигации в коммандой строке - +ls. Это комманда позволяет увидет содержимое данной директорий + +```sh +user@host:~/Documents$ ls +Books todo.txt picture.png +``` + +Она также принимает параметры и аргументы, например, чтобы увидеть скрытые +файлы, добавьте параметр "-a" + +```sh +user@host:~/Documents$ ls -a +Books .secret todo.txt picture.png +``` + +Скрытые файлы и каталоги в Линуксе начинаются с точкой (например, скрытый +каталог ".secret"). + +Также есть параметр "-l" который показывает содержимое в списке с +допольнительной информация, такой как разрещения (больше о них в следующей +части), количество файлов в каталоге, владелец файла (пользователь и группа), +размер, дата создания/модификации, и название самого файла. Например + +```sh +user@host:~/Documents$ ls -l +drwxr-xr-x 2 user user 4.0K Jul 18 04:20 Books +-rw-r--r-- 1 user user 350 Jul 18 04:20 todo.txt +-rw-r--r-- 1 user user 1.2M Jul 18 04:20 picture.png +``` + +Также параметры можно совмещать + +```sh +user@host:~/Documents$ ls -al +drwxr-xr-x 2 user user 4.0K Jul 18 04:20 Books +drwxr-xr-x 5 user user 4.0K Jul 18 04:20 .secret +-rw-r--r-- 1 user user 350 Jul 18 04:20 todo.txt +-rw-r--r-- 1 user user 1.2M Jul 18 04:20 picture.png +``` + +Можно смотреть содержимое другого каталога не переходя на него, передавая его +название/путь в качестве последнего аргумента, например + +```sh +user@host:~/Documents$ ls -l Books +drwxr-xr-x 12 user user 4.0K Jul 18 04:20 Lessons +-rw-r--r-- 1 user user 2.3M Jul 18 04:20 Crime and Punishment.pdf +``` + +### Шорткаты + +Перед тем как завершить первую часть этого туториала, хотелось бы написать про +несколько "шорткатов" при работе в bash'е. + +Первое это перемещение по истории коммандов. Каждый раз когда вы вводите +комманду в терминале, она сохраняется в истории. Вы можете перемещаться по +истории комманд терминала используя стрелки вверх и вниз. Чтобы последнюю +комманду повторить, вы можете один раз нажать на стрелку вверх, а затем можно ее +дописать или переписать и нажать клавишу ввода. Чтобы повторить более старые +комманды, вы можете несколько раз нажать на стрелку вверх до нужной комманды, а +стрелку вниз если пропустили нужную комманду. + +Еще есть очень полезная штука в баше - автозполнение. При нажатии на клавишу +"Таб" баш попытается заполнить для вас комманду. + +Например, допустим вы находитесь в корневом каталоге, и вы хотите перейти в путь +"/home/user/". Вы можете начать печатать "cd h" нажать на "Таб" и у вас +получится "cd home/" затем дописать букву "u" и снова нажать на клавишу "Таб" и +в итоге у вас получится "cd home/user/". + +Если будут несколько возможных вариантов автодополнения, то при одном нажатии +ничего не получится. Это значит, что либо нет такого каталога, либо есть +несколько возможных вариантов для автозаполнение. Во втором случае можно два +раза подряд нажать на клавишу "Таб" и баш вам покажет все возможные варианты, +например + +```sh +user@host:~$ cd Do +Documents/ Downloads/ +user@host:~$ cd Do +``` + +В таком случае мы, например, можем допечатать "cd Doc" и снова нажать на "Таб" и +у нас получится "cd Documents/". Однако, если при двойном нажатие ничего не +выводится, значит что вариантов для автозаполнения. + +В начале может показаться немного не понятно как система автозаполнения +работает, поэтому следует самому попробовать воспользоватся ей на практике +самому. + +На этом пока все, в следующей части расскажу побольше о работе в терминале. -- cgit v1.2.3