bash-guide/README.md

1193 lines
32 KiB
Markdown
Raw Normal View History

2017-04-01 12:27:42 +02:00
<p align="center">
<img src="https://cloud.githubusercontent.com/assets/2059754/24601246/753a7f36-1858-11e7-9d6b-7a0e64fb27f7.png" alt="bash logo"/>
2017-04-01 12:27:42 +02:00
</p>
2018-06-03 19:58:55 +02:00
## Содержание
2018-06-04 20:21:35 +02:00
1. [Основные операции](#1-Основные-операции)
1.1. [Файловые операции](#11-Файловые-операции)
2018-06-09 20:22:46 +02:00
1.2. [Текстовые операции](#12-Текстовые-операции)
1.3. [Операции с каталогами](#13-Операции-с-каталогами)
1.4. [SSH, системная информация и сетевые операции](#14-SSH-системная-информация-и-сетевые-операции)
1.5. [Операции по мониторингу процессов](#15-Операции-по-мониторингу-процессов)
2. [Основы программирования в командной строке](#2-Основы-программирования-в-командной-строке)
2.1. [Переменные](#21-Переменные)
2.2. [Массивы](#22-Массивы)
2.3. [Замена строк](#23-Замена-строк)
2.4. [Функции](#24-Функции)
2.5. [Условные выражения](#25-Условные-выражения)
2.6. [Циклы](#26-Циклы)
3. [Трюки](#3-Трюки)
4. [Отладка (Debug)](#4-Отладка-Debug)
2017-04-01 15:03:37 +02:00
2017-04-01 09:47:13 +02:00
2018-06-03 19:58:55 +02:00
# 1. Основные операции
2017-04-01 09:47:13 +02:00
### a. `export`
2018-06-03 19:58:55 +02:00
Отображает все переменные среды. Если вы хотите получить подробную информацию о конкретной переменной, используйте `echo $VARIABLE_NAME`.
```bash
2017-04-01 09:47:13 +02:00
export
```
2018-06-03 19:58:55 +02:00
Пример:
```bash
2017-04-01 09:47:13 +02:00
$ export
AWS_HOME=/Users/adnanadnan/.aws
LANG=en_US.UTF-8
LC_CTYPE=en_US.UTF-8
LESS=-R
$ echo $AWS_HOME
/Users/adnanadnan/.aws
2017-04-01 09:47:13 +02:00
```
### b. `whatis`
2018-06-03 19:58:55 +02:00
whatis показывает описание для пользовательских команд, системных вызовов, библиотечных функций и другое на страницах руководства.
```bash
whatis something
```
2018-06-03 19:58:55 +02:00
Пример:
```bash
$ whatis bash
bash (1) - GNU Bourne-Again SHell
```
### c. `whereis`
2018-06-03 19:58:55 +02:00
whereis ищет исполняемые файлы, исходные файлы и страницы руководства, используя базу данных, созданную системой автоматически.
```bash
2017-04-01 12:19:47 +02:00
whereis name
2017-04-01 09:47:13 +02:00
```
2018-06-03 19:58:55 +02:00
Пример:
```bash
2017-04-01 09:47:13 +02:00
$ whereis php
/usr/bin/php
```
### d. `which`
2018-06-03 19:58:55 +02:00
which ищет исполняемые файлы в каталогах, заданных переменной среды PATH. Эта команда будет печатать полный путь к исполняемому файлу.
```bash
2017-04-01 12:19:47 +02:00
which program_name
```
2018-06-03 19:58:55 +02:00
Пример:
```bash
$ which php
/c/xampp/php/php
```
### e. clear
2018-06-03 19:58:55 +02:00
Очищает содержимое окна.
2017-04-01 09:47:13 +02:00
2018-06-03 20:21:18 +02:00
## 1.1. Файловые операции
2017-04-01 10:04:51 +02:00
<table>
2017-04-01 10:13:47 +02:00
<tr>
2017-04-04 20:51:26 +02:00
<td><a href="#a-cat">cat</a></td>
<td><a href="#b-chmod">chmod</a></td>
<td><a href="#c-chown">chown</a></td>
<td><a href="#d-cp">cp</a></td>
<td><a href="#e-diff">diff</a></td>
<td><a href="#f-file">file</a></td>
<td><a href="#g-find">find</a></td>
<td><a href="#h-gunzip">gunzip</a></td>
<td><a href="#i-gzcat">gzcat</a></td>
<td><a href="#j-gzip">gzip</a></td>
<td><a href="#k-head">head</a></td>
</tr>
<tr>
<td><a href="#l-lpq">lpq</a></td>
<td><a href="#m-lpr">lpr</a></td>
<td><a href="#n-lprm">lprm</a></td>
<td><a href="#o-ls">ls</a></td>
<td><a href="#p-more">more</a></td>
<td><a href="#q-mv">mv</a></td>
<td><a href="#r-rm">rm</a></td>
<td><a href="#s-tail">tail</a></td>
<td><a href="#t-touch">touch</a></td>
2017-04-01 10:13:47 +02:00
</tr>
2017-04-01 10:04:51 +02:00
</table>
2017-04-04 20:51:26 +02:00
### a. `cat`
2018-06-03 20:21:18 +02:00
Может использоваться для следующих целей в UNIX или Linux.
* Отображение текстовых файлов на экране
* Копирование текстовых файлов
* Объединение текстовых файлов
* Создание новых текстовых файлов
```bash
2017-04-02 05:37:46 +02:00
cat filename
cat file1 file2
cat file1 file2 > newcombinedfile
2017-04-09 10:18:02 +02:00
cat < file1 > file2 #copy file1 to file2
2017-04-01 09:47:13 +02:00
```
2017-04-04 20:51:26 +02:00
### b. `chmod`
2018-06-03 20:21:18 +02:00
Команда chmod позволяет вам изменять права на чтение, запись и выполнение для ваших файлов и папок. Для получения дополнительной информации об этой команде пройдите по [ссылке](https://ss64.com/bash/chmod.html).
```bash
2017-04-04 20:51:26 +02:00
chmod -options filename
2017-04-01 09:47:13 +02:00
```
### c. `chown`
2018-06-03 20:21:18 +02:00
Команда chown означает «владелец прав и позволяет вам изменять владельца данного файла или папки, которые могут быть пользователем и группой. Пользоваться просто, сначала пользователь (владелец), а затем группа, разделенная двоеточием.
```bash
chown -options user:group filename
```
### d. `cp`
2018-06-03 20:21:18 +02:00
Копирует файл из одного места в другое.
```bash
2017-04-01 12:19:47 +02:00
cp filename1 filename2
2017-04-01 09:47:13 +02:00
```
2018-06-03 20:21:18 +02:00
Где `filename1` является исходным путем к файлу и `filename2` путь назначения к файлу.
2017-04-01 09:47:13 +02:00
### e. `diff`
2018-06-03 20:21:18 +02:00
Сравнивает файлы и перечисляет их различия.
```bash
2017-04-01 12:19:47 +02:00
diff filename1 filename2
2017-04-01 09:47:13 +02:00
```
### f. `file`
2018-06-04 20:21:35 +02:00
Определяет тип файла.
```bash
2017-04-04 20:51:26 +02:00
file filename
2017-04-01 09:47:13 +02:00
```
2018-06-03 19:58:55 +02:00
Пример:
```bash
2017-04-04 20:51:26 +02:00
$ file index.html
index.html: HTML document, ASCII text
2017-04-01 09:47:13 +02:00
```
### g. `find`
2018-06-03 20:21:18 +02:00
Поиск файлов в каталоге.
2017-04-05 07:48:07 +02:00
```bash
find directory options pattern
```
2018-06-03 19:58:55 +02:00
Пример:
2017-04-05 07:48:07 +02:00
```bash
$ find . -name README.md
$ find /home/user1 -name '*.png'
```
2017-04-01 09:47:13 +02:00
### h. `gunzip`
2018-06-03 20:21:18 +02:00
Разархивирует файлы сжатые gzip.
```bash
2017-04-01 12:19:47 +02:00
gunzip filename
2017-04-01 09:47:13 +02:00
```
### i. `gzcat`
2018-06-03 20:21:18 +02:00
Позволяет просматривать файлы архива gzipped без необходимости его разархивирования.
```bash
2017-04-01 12:19:47 +02:00
gzcat filename
2017-04-01 09:47:13 +02:00
```
### j. `gzip`
2018-06-03 20:21:18 +02:00
Архивирование файлов.
```bash
2017-04-04 20:51:26 +02:00
gzip filename
2017-04-01 09:47:13 +02:00
```
### k. `head`
2018-06-03 20:21:18 +02:00
Выводит первые 10 строк файла
2017-04-04 20:51:26 +02:00
```bash
head filename
```
### l. `lpq`
2018-06-04 20:21:35 +02:00
Проверка очереди вывода.
```bash
2017-04-01 09:47:13 +02:00
lpq
```
2018-06-03 19:58:55 +02:00
Пример:
```bash
2017-04-01 09:47:13 +02:00
$ lpq
Rank Owner Job File(s) Total Size
active adnanad 59 demo 399360 bytes
1st adnanad 60 (stdin) 0 bytes
```
### m. `lpr`
2018-06-03 20:21:18 +02:00
Печать файла.
2017-04-04 20:51:26 +02:00
```bash
lpr filename
```
### n. `lprm`
2018-06-04 20:21:35 +02:00
Удалить что-то из очереди печати.
```bash
2017-04-01 12:19:47 +02:00
lprm jobnumber
2017-04-01 09:47:13 +02:00
```
### o. `ls`
2018-06-04 20:21:35 +02:00
Список файлов. `ls` имеет множество опций: `-l` список файлов в 'длинном формате', который содержит точный размер файла, имя владельца файла, который имеет право просматривать его и время последнего изменения. `-a` список файлов, включая скрытые файлы. Для получения дополнительной информации об этой команде перейдите по [ссылке](https://ss64.com/bash/ls.html).
```bash
2017-04-04 20:51:26 +02:00
ls option
```
2018-06-03 19:58:55 +02:00
Пример:
2017-04-04 20:51:26 +02:00
<pre>
$ ls -la
2017-04-04 20:51:26 +02:00
rwxr-xr-x 33 adnan staff 1122 Mar 27 18:44 .
drwxrwxrwx 60 adnan staff 2040 Mar 21 15:06 ..
-rw-r--r--@ 1 adnan staff 14340 Mar 23 15:05 .DS_Store
-rw-r--r-- 1 adnan staff 157 Mar 25 18:08 .bumpversion.cfg
-rw-r--r-- 1 adnan staff 6515 Mar 25 18:08 .config.ini
-rw-r--r-- 1 adnan staff 5805 Mar 27 18:44 .config.override.ini
drwxr-xr-x 17 adnan staff 578 Mar 27 23:36 .git
-rwxr-xr-x 1 adnan staff 2702 Mar 25 18:08 .gitignore
</pre>
### p. `more`
2018-06-04 20:21:35 +02:00
Показывает первую часть файла (перемещайтесь нажимая пробел и нажмите q для выхода).
```bash
2017-04-04 20:51:26 +02:00
more filename
```
### q. `mv`
2018-06-04 20:21:35 +02:00
Перемещает файл из одного места в другое.
2017-04-04 20:51:26 +02:00
```bash
mv filename1 filename2
```
2018-06-04 20:21:35 +02:00
Где `filename1` является исходным путем к файлу и `filename2` путь назначения к файлу.
2017-04-04 20:51:26 +02:00
2018-06-04 20:21:35 +02:00
Также может использоваться для переименования файла.
2017-04-06 18:39:33 +02:00
```bash
mv old_name new_name
```
### r. `rm`
2018-06-04 20:21:35 +02:00
Удаляет файл. Использование этой команды для каталога приводит к ошибке.
2017-04-04 20:51:26 +02:00
`rm: directory: is a directory`
2018-06-04 20:21:35 +02:00
Чтобы удалить каталог необходимо ввести `-r` который будет рекурсивно удалять содержимое каталога. При желании вы можете использовать `-f` флаг для принудительного удаления, то есть без каких-либо подтверждений и т.д.
2017-04-04 20:51:26 +02:00
```bash
rm filename
```
### s. `tail`
2018-06-04 20:21:35 +02:00
Выводит последние 10 строк файла. Используйте `-f` для вывода добавленных данных по мере роста файла.
2017-04-04 20:51:26 +02:00
```bash
tail filename
```
### t. `touch`
2018-06-04 20:21:35 +02:00
Обновляет отметки времени создания и изменения файла. Если он не существует, он будет создан.
2017-04-04 20:51:26 +02:00
```bash
touch filename
```
2018-06-03 19:58:55 +02:00
Пример:
2017-04-04 20:51:26 +02:00
```bash
$ touch trick.md
```
2018-06-09 20:22:46 +02:00
## 1.2. Текстовые операции
2017-04-01 14:46:15 +02:00
<table>
2017-04-04 20:51:26 +02:00
<tr>
2017-04-01 14:46:15 +02:00
<td><a href="#a-awk">awk</a></td>
2017-04-04 20:51:26 +02:00
<td><a href="#b-cut">cut</a></td>
<td><a href="#c-echo">echo</a></td>
<td><a href="#d-egrep">egrep</a></td>
<td><a href="#e-fgrep">fgrep</a></td>
<td><a href="#f-fmt">fmt</a></td>
<td><a href="#g-grep">grep</a></td>
<td><a href="#h-nl">nl</a></td>
<td><a href="#i-sed">sed</a></td>
<td><a href="#j-sort">sort</a></td>
2017-04-01 14:46:15 +02:00
</tr>
<tr>
2017-04-04 20:51:26 +02:00
<td><a href="#k-tr">tr</a></td>
<td><a href="#l-uniq">uniq</a></td>
<td><a href="#m-wc">wc</a></td>
2017-04-01 14:46:15 +02:00
</tr>
</table>
### a. `awk`
2018-06-09 20:22:46 +02:00
awk является наиболее полезной командой для обработки текстовых файлов. Работает по строкам. По умолчанию для разделения полей используется пробел. Наиболее распространенным синтаксисом для команды awk является
2017-04-01 14:46:15 +02:00
```bash
awk '/search_pattern/ { action_to_take_if_pattern_matches; }' file_to_parse
```
2018-06-09 20:22:46 +02:00
Возьмем следующий файл `/etc/passwd`. Вот пример данных, которые содержит этот файл:
2017-04-01 14:46:15 +02:00
```
root:x:0:0:root:/root:/usr/bin/zsh
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
```
2018-06-09 20:22:46 +02:00
Итак, теперь вы можете получить только имя пользователя из этого файла. Где `-F` указывает на какой основе мы собираемся разделить поля. В нашем случае `:`. `{print $ 1}` означает вывод первого поля соответствия.
2017-04-01 14:46:15 +02:00
```bash
awk -F':' '{ print $1 }' /etc/passwd
```
2018-06-09 20:22:46 +02:00
После выполнения указанной команды вы получите следующий вывод.
2017-04-01 14:46:15 +02:00
```
root
daemon
bin
sys
sync
```
2018-06-09 20:22:46 +02:00
Подробнее о том, как использовать `awk`, перейдите по [ссылке](https://www.cyberciti.biz/faq/bash-scripting-using-awk).
2017-04-01 14:46:15 +02:00
2017-04-04 20:51:26 +02:00
### b. `cut`
2018-06-09 20:22:46 +02:00
Удалить разделы из каждой строки файлов.
2017-04-04 20:51:26 +02:00
*example.txt*
```bash
red riding hood went to the park to play
```
2018-06-09 20:22:46 +02:00
*покажите мне столбцы 2, 7 и 9 с пробелом в качестве разделителя*
2017-04-04 20:51:26 +02:00
```bash
cut -d " " -f2,7,9 example.txt
```
```bash
riding park play
```
### c. `echo`
2018-06-09 20:22:46 +02:00
Отображение строки текста
2017-04-04 20:51:26 +02:00
2018-06-09 20:22:46 +02:00
*отобразить «Hello World»*
2017-04-04 20:51:26 +02:00
```bash
echo Hello World
```
```bash
Hello World
```
2018-06-09 20:22:46 +02:00
*отобразите «Hello World» каждое слово с новой строки*
2017-04-04 20:51:26 +02:00
```bash
echo -ne "Hello\nWorld\n"
```
```bash
Hello
World
```
### d. `egrep`
2018-06-09 20:22:46 +02:00
Вывод строк, соответствующие шаблону - Extended Expression (псевдоним для: 'grep -E')
2017-04-04 20:51:26 +02:00
*example.txt*
```bash
Lorem ipsum
dolor sit amet,
consetetur
sadipscing elitr,
sed diam nonumy
eirmod tempor
invidunt ut labore
et dolore magna
aliquyam erat, sed
diam voluptua. At
vero eos et
accusam et justo
duo dolores et ea
rebum. Stet clita
kasd gubergren,
no sea takimata
sanctus est Lorem
ipsum dolor sit
amet.
```
2018-06-09 20:22:46 +02:00
*отобразить строки в которых есть «Lorem», либо «dolor».*
2017-04-04 20:51:26 +02:00
```bash
egrep '(Lorem|dolor)' example.txt
or
grep -E '(Lorem|dolor)' example.txt
```
```bash
Lorem ipsum
dolor sit amet,
et dolore magna
duo dolores et ea
sanctus est Lorem
ipsum dolor sit
```
### e. `fgrep`
2018-06-09 20:22:46 +02:00
Вывод строк, соответствующие шаблону - FIXED pattern matching (псевдоним для: 'grep -F')
2017-04-04 20:51:26 +02:00
*example.txt*
```bash
Lorem ipsum
dolor sit amet,
consetetur
sadipscing elitr,
sed diam nonumy
eirmod tempor
foo (Lorem|dolor)
invidunt ut labore
et dolore magna
aliquyam erat, sed
diam voluptua. At
vero eos et
accusam et justo
duo dolores et ea
rebum. Stet clita
kasd gubergren,
no sea takimata
sanctus est Lorem
ipsum dolor sit
amet.
```
2018-06-09 20:22:46 +02:00
*Найти строку с '(Lorem|dolor)' в example.txt*
2017-04-04 20:51:26 +02:00
```bash
fgrep '(Lorem|dolor)' example.txt
or
grep -F '(Lorem|dolor)' example.txt
```
```bash
foo (Lorem|dolor)
```
### f. `fmt`
2018-06-09 20:22:46 +02:00
Простое форматирование текста
2017-04-04 20:51:26 +02:00
2018-06-09 20:22:46 +02:00
*Пример: example.txt (1 строка)*
2017-04-04 20:51:26 +02:00
```bash
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
```
2018-06-09 20:22:46 +02:00
*выводить строки example.txt шириной 20 символов*
2017-04-04 20:51:26 +02:00
```bash
cat example.txt | fmt -w 20
```
```bash
Lorem ipsum
dolor sit amet,
consetetur
sadipscing elitr,
sed diam nonumy
eirmod tempor
invidunt ut labore
et dolore magna
aliquyam erat, sed
diam voluptua. At
vero eos et
accusam et justo
duo dolores et ea
rebum. Stet clita
kasd gubergren,
no sea takimata
sanctus est Lorem
ipsum dolor sit
amet.
```
### g. `grep`
2018-06-09 20:22:46 +02:00
Ищет текст внутри файлов. Вы можете использовать grep для поиска строк текста, которые соответствуют одному или нескольким регулярным выражениям, и выводит только соответствующие строки.
```bash
2017-04-01 12:19:47 +02:00
grep pattern filename
2017-04-01 09:47:13 +02:00
```
2018-06-03 19:58:55 +02:00
Пример:
```bash
2017-04-01 09:47:13 +02:00
$ grep admin /etc/passwd
_kadmin_admin:*:218:-2:Kerberos Admin Service:/var/empty:/usr/bin/false
_kadmin_changepw:*:219:-2:Kerberos Change Password Service:/var/empty:/usr/bin/false
_krb_kadmin:*:231:-2:Open Directory Kerberos Admin Service:/var/empty:/usr/bin/false
```
2018-06-09 20:22:46 +02:00
Вы также можете игнорировать словосочетания с помощью опции `-i`. `-r` может использоваться для поиска всех файлов в указанном каталоге, пример:
```bash
2017-04-01 09:47:13 +02:00
$ grep -r admin /etc/
```
2018-06-09 20:22:46 +02:00
И `-w` для поиска только слов. Более подробно о `grep`, перейдите по [ссылке](https://www.cyberciti.biz/faq/grep-in-bash).
2017-04-01 09:47:13 +02:00
2017-04-04 20:51:26 +02:00
### h. `nl`
2018-06-09 20:22:46 +02:00
Номер строк в файле
2017-04-04 20:51:26 +02:00
*example.txt*
2017-04-01 14:46:15 +02:00
```bash
2017-04-04 20:51:26 +02:00
Lorem ipsum
dolor sit amet,
consetetur
sadipscing elitr,
sed diam nonumy
eirmod tempor
invidunt ut labore
et dolore magna
aliquyam erat, sed
diam voluptua. At
vero eos et
accusam et justo
duo dolores et ea
rebum. Stet clita
kasd gubergren,
no sea takimata
sanctus est Lorem
ipsum dolor sit
amet.
2017-04-01 14:46:15 +02:00
```
2017-04-04 20:51:26 +02:00
2018-06-09 20:22:46 +02:00
*вывести example.txt с номерами строк*
2017-04-01 14:46:15 +02:00
```bash
2017-04-04 20:51:26 +02:00
nl -s". " example.txt
```
```bash
1. Lorem ipsum
2. dolor sit amet,
3. consetetur
4. sadipscing elitr,
5. sed diam nonumy
6. eirmod tempor
7. invidunt ut labore
8. et dolore magna
9. aliquyam erat, sed
10. diam voluptua. At
11. vero eos et
12. accusam et justo
13. duo dolores et ea
14. rebum. Stet clita
15. kasd gubergren,
16. no sea takimata
17. sanctus est Lorem
18. ipsum dolor sit
19. amet.
2017-04-01 14:46:15 +02:00
```
2017-04-04 20:51:26 +02:00
### i. `sed`
2018-06-09 20:22:46 +02:00
Потоковый редактор для фильтрации и преобразования текста.
*example.txt*
```bash
Hello This is a Test 1 2 3 4
```
2018-06-09 20:22:46 +02:00
*заменить все пробелы дефисом*
```bash
sed 's/ /-/g' example.txt
```
```bash
Hello-This-is-a-Test-1-2-3-4
```
2018-06-09 20:22:46 +02:00
*заменить все цифры на "d"*
```bash
sed 's/[0-9]/d/g' example.txt
```
```bash
Hello This is a Test d d d d
```
2017-04-01 14:46:15 +02:00
2017-04-04 20:51:26 +02:00
### j. `sort`
2018-06-09 20:22:46 +02:00
Сортирует строки в текстовом файле.
*example.txt*
```bash
f
b
c
g
a
e
d
```
2018-06-05 20:58:40 +02:00
*сортировать example.txt*
```bash
sort example.txt
```
```bash
a
b
c
d
e
f
g
```
2018-06-05 20:58:40 +02:00
*рандомизировать отсортированный example.txt*
```bash
sort example.txt | sort -R
```
```bash
b
f
a
2017-04-04 20:51:26 +02:00
c
d
g
e
```
2017-04-01 14:46:15 +02:00
2017-04-04 20:51:26 +02:00
### k. `tr`
2018-06-09 20:22:46 +02:00
Переводит или удаляет символы.
2017-04-01 14:46:15 +02:00
*example.txt*
```bash
Hello World Foo Bar Baz!
```
2018-06-05 20:58:40 +02:00
*заменяет все буквы нижнего регистра в верхний регистр*
```bash
cat example.txt | tr 'a-z' 'A-Z'
```
```bash
HELLO WORLD FOO BAR BAZ!
```
2018-06-05 20:58:40 +02:00
*превращает все пробелы в новые строки*
```bash
cat example.txt | tr ' ' '\n'
```
```bash
Hello
World
Foo
Bar
Baz!
```
2017-04-04 20:51:26 +02:00
### l. `uniq`
2018-06-09 20:22:46 +02:00
Сообщает об повторяющиеся строках или пропускает их.
*example.txt*
```bash
2017-04-04 20:51:26 +02:00
a
a
b
a
b
c
d
c
```
2018-06-09 20:22:46 +02:00
*показавыет только уникальные строки example.txt (сначала нужно отсортировать его, иначе он не увидит совпадения)*
```bash
2017-04-04 20:51:26 +02:00
sort example.txt | uniq
```
```bash
2017-04-04 20:51:26 +02:00
a
b
c
d
```
2018-06-05 20:58:40 +02:00
*показавает уникальные элементы для каждой строки и сообщает, сколько экземпляров найдено*
```bash
2017-04-04 20:51:26 +02:00
sort example.txt | uniq -c
```
```bash
2017-04-04 20:51:26 +02:00
3 a
2 b
2 c
1 d
```
2017-04-04 20:51:26 +02:00
### m. `wc`
2018-06-05 20:58:40 +02:00
Сообщает, сколько строк, слов и символов содержит файл.
```bash
2017-04-04 20:51:26 +02:00
wc filename
```
2018-06-03 19:58:55 +02:00
Пример:
```bash
2017-04-04 20:51:26 +02:00
$ wc demo.txt
7459 15915 398400 demo.txt
```
2018-06-05 20:58:40 +02:00
Где `7459` линий, `15915` слов и `398400` символов.
2017-04-01 14:46:15 +02:00
2018-06-05 20:58:40 +02:00
## 1.3. Операции с каталогами
2017-04-01 09:47:13 +02:00
2017-04-01 10:21:38 +02:00
<table>
<tr>
2017-04-04 20:51:26 +02:00
<td><a href="#a-cd">cd</a></td>
<td><a href="#b-mkdir">mkdir</a></td>
<td><a href="#c-pwd">pwd</a></td>
2017-04-01 10:21:38 +02:00
</tr>
</table>
2017-04-04 20:51:26 +02:00
### a. `cd`
Moves you from one directory to other. Running this
```bash
2017-04-01 09:47:13 +02:00
$ cd
```
moves you to home directory. This command accepts an optional `dirname`, which moves you to that directory.
```bash
2017-04-01 12:19:47 +02:00
cd dirname
2017-04-01 09:47:13 +02:00
```
2017-04-04 20:51:26 +02:00
### b. `mkdir`
Makes a new directory.
```bash
mkdir dirname
```
2017-04-01 09:47:13 +02:00
### c. `pwd`
Tells you which directory you currently are in.
```bash
2017-04-01 09:47:13 +02:00
pwd
```
2017-04-01 14:46:15 +02:00
## 1.4. SSH, System Info & Network Operations
2017-04-01 09:47:13 +02:00
<table>
<tr>
2017-04-04 20:51:26 +02:00
<td><a href="#a-bg">bg</a></td>
<td><a href="#b-cal">cal</a></td>
<td><a href="#c-date">date</a></td>
<td><a href="#d-df">df</a></td>
<td><a href="#e-dig">dig</a></td>
<td><a href="#f-du">du</a></td>
<td><a href="#g-fg">fg</a></td>
<td><a href="#h-finger">finger</a></td>
<td><a href="#i-jobs">jobs</a></td>
<td><a href="#j-last">last</a></td>
</tr>
<tr>
2017-05-02 08:34:26 +02:00
<td><a href="#k-man">man</a></td>
<td><a href="#l-passwd">passwd</a></td>
<td><a href="#m-ping">ping</a></td>
<td><a href="#n-ps">ps</a></td>
<td><a href="#o-quota">quota</a></td>
<td><a href="#p-scp">scp</a></td>
<td><a href="#q-ssh">ssh</a></td>
<td><a href="#r-top">top</a></td>
<td><a href="#s-uname">uname</a></td>
<td><a href="#t-uptime">uptime</a></td>
</tr>
<tr>
2017-05-02 08:34:26 +02:00
<td><a href="#u-w">w</a></td>
<td><a href="#v-wget">wget</a></td>
<td><a href="#w-whoami">whoami</a></td>
<td><a href="#x-whois">whois</a></td>
</tr>
</table>
2017-04-04 20:51:26 +02:00
### a. `bg`
Lists stopped or background jobs; resume a stopped job in the background.
2017-04-01 09:47:13 +02:00
2017-04-04 20:51:26 +02:00
### b. `cal`
Shows the month's calendar.
2017-04-01 09:47:13 +02:00
2017-04-04 20:51:26 +02:00
### c. `date`
Shows the current date and time.
2017-04-01 09:47:13 +02:00
2017-04-04 20:51:26 +02:00
### d. `df`
Shows disk usage.
2017-04-01 09:47:13 +02:00
2017-04-04 20:51:26 +02:00
### e. `dig`
Gets DNS information for domain.
```bash
2017-04-04 20:51:26 +02:00
dig domain
2017-04-01 09:47:13 +02:00
```
2017-04-04 20:51:26 +02:00
### f. `du`
Shows the disk usage of files or directories. For more information on this command check this [link](http://www.linfo.org/du.html)
```bash
du [option] [filename|directory]
```
Options:
- `-h` (human readable) Displays output it in kilobytes (K), megabytes (M) and gigabytes (G).
- `-s` (supress or summarize) Outputs total disk space of a directory and supresses reports for subdirectories.
2018-06-03 19:58:55 +02:00
Пример:
2017-04-05 21:38:43 +02:00
```bash
du -sh pictures
1.4M pictures
2017-04-01 09:47:13 +02:00
```
2017-04-04 20:51:26 +02:00
### g. `fg`
Brings the most recent job in the foreground.
2017-04-01 09:47:13 +02:00
2017-04-04 20:51:26 +02:00
### h. `finger`
Displays information about user.
```bash
2017-04-04 20:51:26 +02:00
finger username
2017-04-01 09:47:13 +02:00
```
### i. `jobs`
Lists the jobs running in the background, giving the job number.
2017-04-01 09:47:13 +02:00
### j. `last`
2017-04-04 20:51:26 +02:00
Lists your last logins of specified user.
```bash
last yourUsername
```
2017-04-01 09:47:13 +02:00
### k. `man`
2017-04-04 20:51:26 +02:00
Shows the manual for specified command.
```bash
man command
```
2017-04-01 09:47:13 +02:00
### l. `passwd`
2017-11-19 19:32:54 +01:00
Allows the current logged user to change their password.
2017-04-01 09:47:13 +02:00
### m. `ping`
Pings host and outputs results.
```bash
2017-04-01 12:19:47 +02:00
ping host
2017-04-01 09:47:13 +02:00
```
### n. `ps`
2017-04-04 20:51:26 +02:00
Lists your processes.
```bash
2017-04-04 20:51:26 +02:00
ps -u yourusername
2017-04-01 09:47:13 +02:00
```
Use the flags ef. e for every process and f for full listing.
```bash
ps -ef
```
2017-04-01 09:47:13 +02:00
### o. `quota`
2017-04-04 20:51:26 +02:00
Shows what your disk quota is.
```bash
2017-04-04 20:51:26 +02:00
quota -v
2017-04-01 09:47:13 +02:00
```
### p. `scp`
Transfer files between a local host and a remote host or between two remote hosts.
*copy from local host to remote host*
```bash
scp source_file user@host:directory/target_file
```
*copy from remote host to local host*
```bash
scp user@host:directory/source_file target_file
scp -r user@host:directory/source_folder target_folder
```
2017-04-04 19:33:58 +02:00
This command also accepts an option `-P` that can be used to connect to specific port.
```bash
scp -P port user@host:directory/source_file target_file
```
### q. `ssh`
2017-04-04 20:51:26 +02:00
ssh (SSH client) is a program for logging into and executing commands on a remote machine.
```bash
ssh user@host
```
This command also accepts an option `-p` that can be used to connect to specific port.
```bash
ssh -p port user@host
```
### r. `top`
2017-04-04 20:51:26 +02:00
Displays your currently active processes.
### s. `uname`
2017-04-04 20:51:26 +02:00
Shows kernel information.
```bash
uname -a
```
### t. `uptime`
2017-04-04 20:51:26 +02:00
Shows current uptime.
### u. `w`
2017-04-04 20:51:26 +02:00
Displays who is online.
### v. `wget`
2017-04-04 20:51:26 +02:00
Downloads file.
```bash
wget file
```
### w. `whoami`
2017-04-04 20:51:26 +02:00
Return current logged in username.
### x. `whois`
2017-04-04 20:51:26 +02:00
Gets whois information for domain.
```bash
whois domain
```
## 1.5. Process Monitoring Operations
<table>
<tr>
<td><a href="#a-kill">kill</a></td>
<td><a href="#b-killall">killall</a></td>
<td><a href="#c-&">&amp;</a></td>
2017-04-24 21:44:09 +02:00
<td><a href="#d-nohup">nohup</a></td>
</tr>
</table>
### a. `kill`
Kills (ends) the processes with the ID you gave.
```bash
kill PID
```
### b. `killall`
Kill all processes with the name.
```bash
killall processname
```
2017-04-24 21:45:41 +02:00
### c. &
The `&` symbol instructs the command to run as a background process in a subshell.
```bash
command &
```
### d. `nohup`
nohup stands for "No Hang Up". This allows to run command/process or shell script that can continue running in the background after you log out from a shell.
```bash
nohup command
```
Combine it with `&` to create background processes
```bash
nohup command &
```
2017-04-01 09:47:13 +02:00
# 2. Basic Shell Programming
2017-04-01 15:03:37 +02:00
2017-04-04 19:33:58 +02:00
The first line that you will write in bash script files is called `shebang`. This line in any script determines the script's ability to be executed like a standalone executable without typing sh, bash, python, php etc beforehand in the terminal.
2017-04-01 15:03:37 +02:00
```bash
#!/usr/bin/env bash
2017-04-01 15:03:37 +02:00
```
2017-04-01 09:47:13 +02:00
## 2.1. Variables
Creating variables in bash is similar to other languages. There are no data types. A variable in bash can contain a number, a character, a string of characters, etc. You have no need to declare a variable, just assigning a value to its reference will create it.
2017-04-01 09:47:13 +02:00
2018-06-03 19:58:55 +02:00
Пример:
```bash
2017-04-01 09:47:13 +02:00
str="hello world"
```
The above line creates a variable `str` and assigns "hello world" to it. The value of variable is retrieved by putting the `$` in the beginning of variable name.
2017-04-01 09:47:13 +02:00
2018-06-03 19:58:55 +02:00
Пример:
```bash
2017-04-01 09:47:13 +02:00
echo $str # hello world
```
## 2.2. Array
Like other languages bash has also arrays. An array is variable containing multiple values. There's no maximum limit on the size of array. Array in bash are zero based. The first element is indexed with element 0. There are several ways for creating arrays in bash. Which are given below.
2017-04-01 09:47:13 +02:00
Examples:
```bash
2017-04-01 09:47:13 +02:00
array[0] = val
array[1] = val
array[2] = val
array=([2]=val [0]=val [1]=val)
array=(val val val)
2017-04-01 09:47:13 +02:00
```
To display a value at specific index use following syntax:
2017-04-01 09:47:13 +02:00
```bash
2017-04-01 09:47:13 +02:00
${array[i]} # where i is the index
```
If no index is supplied, array element 0 is assumed. To find out how many values there are in the array use the following syntax:
2017-04-01 09:47:13 +02:00
```bash
2017-04-01 09:47:13 +02:00
${#array[@]}
```
Bash has also support for the ternary conditions. Check some examples below.
```bash
2017-04-01 09:47:13 +02:00
${varname:-word} # if varname exists and isn't null, return its value; otherwise return word
${varname:=word} # if varname exists and isn't null, return its value; otherwise set it word and then return its value
${varname:+word} # if varname exists and isn't null, return word; otherwise return null
${varname:offset:length} # performs substring expansion. It returns the substring of $varname starting at offset and up to length characters
```
## 2.3 String Substitution
2017-04-01 09:47:13 +02:00
Check some of the syntax on how to manipulate strings
```bash
2017-04-01 09:47:13 +02:00
${variable#pattern} # if the pattern matches the beginning of the variable's value, delete the shortest part that matches and return the rest
${variable##pattern} # if the pattern matches the beginning of the variable's value, delete the longest part that matches and return the rest
${variable%pattern} # if the pattern matches the end of the variable's value, delete the shortest part that matches and return the rest
${variable%%pattern} # if the pattern matches the end of the variable's value, delete the longest part that matches and return the rest
${variable/pattern/string} # the longest match to pattern in variable is replaced by string. Only the first match is replaced
${variable//pattern/string} # the longest match to pattern in variable is replaced by string. All matches are replaced
${#varname} # returns the length of the value of the variable as a character string
```
## 2.4. Functions
2017-04-01 09:47:13 +02:00
As in almost any programming language, you can use functions to group pieces of code in a more logical way or practice the divine art of recursion. Declaring a function is just a matter of writing function my_func { my_code }. Calling a function is just like calling another program, you just write its name.
```bash
2017-05-14 13:17:29 +02:00
function name() {
2017-04-01 09:47:13 +02:00
shell commands
}
```
2018-06-03 19:58:55 +02:00
Пример:
```bash
2017-04-01 09:47:13 +02:00
#!/bin/bash
function hello {
echo world!
}
hello
function say {
echo $1
}
say "hello world!"
```
When you run the above example the `hello` function will output "world!". The above two functions `hello` and `say` are identical. The main difference is function `say`. This function, prints the first argument it receives. Arguments, within functions, are treated in the same manner as arguments given to the script.
2017-04-01 09:47:13 +02:00
## 2.5. Conditionals
2017-04-01 09:47:13 +02:00
The conditional statement in bash is similar to other programming languages. Conditions have many form like the most basic form is `if` expression `then` statement where statement is only executed if expression is true.
```bash
2017-11-19 19:34:39 +01:00
if [ expression ]; then
2017-04-01 09:47:13 +02:00
will execute only if expression is true
else
will execute if expression is false
fi
```
Sometime if conditions becoming confusing so you can write the same condition using the `case statements`.
```bash
2017-04-01 09:47:13 +02:00
case expression in
pattern1 )
statements ;;
pattern2 )
statements ;;
...
esac
```
Expression Examples:
```bash
2017-04-01 09:47:13 +02:00
statement1 && statement2 # both statements are true
statement1 || statement2 # at least one of the statements is true
2017-04-01 09:47:13 +02:00
str1=str2 # str1 matches str2
str1!=str2 # str1 does not match str2
str1<str2 # str1 is less than str2
str1>str2 # str1 is greater than str2
-n str1 # str1 is not null (has length greater than 0)
-z str1 # str1 is null (has length 0)
-a file # file exists
-d file # file exists and is a directory
-e file # file exists; same -a
-f file # file exists and is a regular file (i.e., not a directory or other special type of file)
-r file # you have read permission
-s file # file exists and is not empty
-w file # you have write permission
2017-04-01 09:47:13 +02:00
-x file # you have execute permission on file, or directory search permission if it is a directory
-N file # file was modified since it was last read
-O file # you own file
-G file # file's group ID matches yours (or one of yours, if you are in multiple groups)
file1 -nt file2 # file1 is newer than file2
file1 -ot file2 # file1 is older than file2
-lt # less than
-le # less than or equal
-eq # equal
-ge # greater than or equal
-gt # greater than
-ne # not equal
```
## 2.6. Loops
2017-04-01 09:47:13 +02:00
There are three types of loops in bash. `for`, `while` and `until`.
Different `for` Syntax:
```bash
2017-04-01 09:47:13 +02:00
for x := 1 to 10 do
begin
statements
end
for name [in list]
do
statements that can use $name
done
for (( initialisation ; ending condition ; update ))
do
statements...
done
```
`while` Syntax:
```bash
2017-04-01 09:47:13 +02:00
while condition; do
statements
done
```
`until` Syntax:
```bash
2017-04-01 09:47:13 +02:00
until condition; do
statements
done
```
# 3. Tricks
2017-04-01 09:47:13 +02:00
2017-04-04 05:06:11 +02:00
## Set an alias
2017-04-01 09:47:13 +02:00
Open `bash_profile` by running following command `nano ~/.bash_profile`
> alias dockerlogin='ssh www-data@adnan.local -p2222' # add your alias in .bash_profile
2017-04-04 05:06:11 +02:00
## To quickly go to a specific directory
2017-04-01 09:47:13 +02:00
nano ~/.bashrc
> export hotellogs="/workspace/hotel-api/storage/logs"
```bash
2017-04-01 09:47:13 +02:00
source ~/.bashrc
cd $hotellogs
```
2017-04-01 09:47:13 +02:00
2017-04-16 10:02:21 +02:00
## Exit traps
Make your bash scripts more robust by reliably performing cleanup.
```bash
function finish {
# your cleanup here. e.g. kill any forked processes
jobs -p | xargs kill
}
trap finish EXIT
```
## Saving your environment variables
When you do `export FOO = BAR`, your variable is only exported in this current shell and all its children, to persist in the future you can simply append in your `~/.bash_profile` file the command to export your variable
```bash
echo export FOO=BAR >> ~/.bash_profile
```
## Accessing your scripts
You can easily access your scripts by creating a bin folder in your home with `mkdir ~/bin`, now all the scripts you put in this folder you can access in any directory.
If you can not access, try append the code below in your `~/.bash_profile` file and after do `source ~/.bash_profile`.
```bash
# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
PATH="$HOME/bin:$PATH"
fi
```
# 4. Debugging
2017-04-01 09:47:13 +02:00
You can easily debug the bash script by passing different options to `bash` command. For example `-n` will not run commands and check for syntax errors only. `-v` echo commands before running them. `-x` echo commands after command-line processing.
```bash
2017-04-01 09:47:13 +02:00
bash -n scriptname
bash -v scriptname
bash -x scriptname
```
2017-04-01 15:03:37 +02:00
2018-06-05 20:58:40 +02:00
## Помощь
2017-04-01 15:03:37 +02:00
2018-06-05 20:58:40 +02:00
- Сообщить об ошибке [Как?](https://help.github.com/articles/creating-an-issue/)
- Создать pull request с улучшениями [Как?](https://help.github.com/articles/about-pull-requests/)
- Поделиться
2017-04-01 15:03:37 +02:00
2018-06-05 20:58:40 +02:00
## Переводы
- [English ](https://github.com/itooww/bash-guide)
- [Chinese | 简体中文](https://github.com/vuuihc/bash-guide)
2017-05-07 20:04:37 +02:00
- [Turkish | Türkçe](https://github.com/omergulen/bash-guide)
2017-06-30 05:03:43 +02:00
- [Japanese | 日本語](https://github.com/itooww/bash-guide)
2018-06-05 20:58:40 +02:00
- [Russian | Русский](https://github.com/itooww/bash-guide)
2017-05-07 20:04:37 +02:00
2017-04-01 15:03:37 +02:00
## License
[![License: CC BY 4.0](https://img.shields.io/badge/License-CC%20BY%204.0-lightgrey.svg)](https://creativecommons.org/licenses/by/4.0/)