-
-
Save kDallas1203/0f1d30dd851110c841c814bfcebaf89d to your computer and use it in GitHub Desktop.
Revisions
-
s3rgeym revised this gist
Jul 13, 2019 . 1 changed file with 2 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -81,6 +81,8 @@  На самом деле все не так плохо, но неприятные инциденты имеют место хотя и очень редко. ## Создание образа Качаем [образ](https://www.archlinux.org/download/) и записываем его с помощью команды: -
s3rgeym revised this gist
Jul 13, 2019 . 2 changed files with 3 additions and 1 deletion.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -397,6 +397,7 @@ yay -Sy linux-headers \ # нужны для компиляции некотор \ # pgmodeler \ # визуальный редактор для моделирования в Postgres \ # phpenv \ # менеджер версий для PHP \ # pyenv \ # менеджер версий для Python asdf-vm \ # Заменяет собой все выше перечисленные менеджеры версий + умеет управлять базами \ # redis \ # СУБД в оперативной памяти, используемая для межпроцессового взаимодействия smartmontools \ # утилита для проверки состояния SSD telegram-desktop-bin \ # лучший мессенджер This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -20,7 +20,8 @@ name = re.sub(r'\[(.*?)\]\(.*?\)', r'\1', name) uri = name.lower() # Вырезаем все не буквенно-цифровые символы # «-» то же не унжно вырезать uri = re.sub(r'[^\w\s-]', '', uri) # Заменяем пробелы на «-» uri = uri.replace(' ', '-') print(' ' * (depth - 1) + f'1. [{name}](#{uri})') -
s3rgeym revised this gist
Jul 13, 2019 . 1 changed file with 19 additions and 5 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -127,7 +127,7 @@ fdisk /dev/nvme0n1 В меню fdisk вводим `n` для создания нового раздела, порядковый номер раздела, потом начальное и конечные смещения. При задании конечного смещения можно отрицательное значение, например, `-10G`, так мы оставим свободными 10 Гб в конце диска. Для записи изменений на жесткий диск вводим `w` и выходим - `q`. Теперь нужно разметить раздел по LVM. Касательно LVM: единственное удобство в нем для меня – это возможность динамически менять размер разделов. Самая частая проблема, которая у меня была раньше – это то, что я не угадывал размер для корня. Когда в нем кончалось место, я с установочной флешки через gparted пытался отщепнуть от виндового раздела кусок (а у меня разделы всегда шли так: recovery, efi, reserved, windows, root, home), из этого куска создавал временный раздел, копировал в него файлы с хомяка, удалял хомяка, изменял размер корневого, опять создавал хомяка и из временного раздела копировал в него файлы, потом удалял временный раздел, расширял виндовый, правил `/etc/fstab`… А с LVM я могу просто выполнить пару команд: ужать хомяка, расширить корневой, причем, на лету. Но эксперты могут возразить: «Хомяк на отдельном разделе не нужен!» — Да, если хочешь потерять все данные при переустановке. Создадим группу: @@ -370,7 +370,7 @@ yay -Sy linux-headers \ # нужны для компиляции некотор arc-gtk-theme-git \ # тема для интерфейса apache \ # самый популярный веб-сервер apache-tools \ # содержит ab, нагрузочный клиент \ # blender \ # самый простой 3D-редактор dconf-editor \ # все настройки gnome в одном месте dmraid \ # утилита для работы с raid-массивами дисков docker-compose \ # содержит docker и docker compose @@ -384,7 +384,7 @@ yay -Sy linux-headers \ # нужны для компиляции некотор gparted \ # графическая оболочка для разметки дисков htop \ # показывает запущенные процессы, загрузку cpu и потребление памяти \ # inkscape \ # векторный графический редактор \ # mariadb \ # свободная реализация самой популярной СУБД MySQL mc \ # аналог виндового Far + mcedit, замена nano \ # mongodb-bin \ # лучшая NoSQL база данных net-tools \ # содержит netstat @@ -393,7 +393,7 @@ yay -Sy linux-headers \ # нужны для компиляции некотор ntfs-3g \ # добавляет поддержку файловой системы ntfs \ # nvm \ # менеджер версий для Node.js \ # postgresql \ # лучшая SQL база данных \ # pgadmin4 \ # админка для Postgres \ # pgmodeler \ # визуальный редактор для моделирования в Postgres \ # phpenv \ # менеджер версий для PHP \ # pyenv \ # менеджер версий для Python @@ -410,7 +410,9 @@ yay -Sy linux-headers \ # нужны для компиляции некотор vlc \ # видеоплеер websocat-bin \ # утилита для тестированя вебсокетов woeusb \ # создание загрузочных флешек с Windows xclip \ # копирование файла в буффер обмена из консоли seahorse \ # Приложение для управления паролями, а так же PGP и SSH ключами ``` # Масштабировавние 150% как в Windows @@ -1711,6 +1713,18 @@ $ chmod +x /path/to/file # Выполнит скрипт в текущем процессе (переменные и функции, объявленные внутри скрипта станут доступны в терминале) $ source /path/to/file # ============================================================================== # # Запуск команд # # ============================================================================== # Запустить процесс и вернуть его дескриптор (при закрытии терминала будет остановлена) $ command & # То же самое за исключением того, что процесс не будет остановлен при закрытии терминала $ nohup command & # ============================================================================== # # Пакеты -
s3rgeym revised this gist
Jul 13, 2019 . 1 changed file with 66 additions and 52 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -68,8 +68,9 @@ 1. [Что делать, если каталоги открываются в VSCode?](#что-делать-если-каталоги-открываются-в-vscode) 1. [Enter password to unlock your login keyring](#enter-password-to-unlock-your-login-keyring) 1. [Справка по командам и т.д.](#справка-по-командам-и-тд) 1. [Cheat.sh](#cheatsh) 1. [Marker](#marker) 1. [TLDR](#tldr) 1. [Шпаргалка по командам Shell](#шпаргалка-по-командам-shell) # Установка @@ -364,8 +365,8 @@ yay -Sy linux-headers \ # нужны для компиляции некотор adobe-source-code-pro-fonts \ # шрифт для терминала, нужен для темы Oh My Zsh! agnoster ttf-droid \ # шрифт по-умолчанию для VScode \ # шрифты по-умолчанию для Chrome \ # consolas-font \ \ # ttf-ms-fonts \ arc-gtk-theme-git \ # тема для интерфейса apache \ # самый популярный веб-сервер apache-tools \ # содержит ab, нагрузочный клиент @@ -376,24 +377,24 @@ yay -Sy linux-headers \ # нужны для компиляции некотор exfat-utils \ # добавляет поддержку файловой системы exfat firefox \ # один из лучших браузеров, единственный конкурент Chrome и единственный популярный non-chromium браузер flat-remix-git \ # тема с иконками \ # gimp \ # скромненький аналог Photoshop gnome-panel \ # я ставил только чтобы ярлыки из GUI создавать google-chrome \ # лучший браузер, противники проприетарщины предпочитают chromium chrome-gnome-shell \ # позволяет устанавливать расширения для Gnome gparted \ # графическая оболочка для разметки дисков htop \ # показывает запущенные процессы, загрузку cpu и потребление памяти \ # inkscape \ # векторный графический редактор mariadb \ # свободная реализация самой популярной СУБД MySQL mc \ # аналог виндового Far + mcedit, замена nano \ # mongodb-bin \ # лучшая NoSQL база данных net-tools \ # содержит netstat neofetch \ # выводит в консоль информацию о системе nginx \ # самый быстрый веб-сервер ntfs-3g \ # добавляет поддержку файловой системы ntfs \ # nvm \ # менеджер версий для Node.js \ # postgresql \ # лучшая SQL база данных pgadmin4 \ # админка для Postgres \ # pgmodeler \ # визуальный редактор для моделирования в Postgres \ # phpenv \ # менеджер версий для PHP \ # pyenv \ # менеджер версий для Python \ # redis \ # СУБД в оперативной памяти, используемая для межпроцессового взаимодействия @@ -596,8 +597,6 @@ $ chsh -s $(which zsh) Чтобы изменения вступили в силу нужно залогиниться по-новой. ## [Oh My Zsh](https://github.com/robbyrussell/oh-my-zsh) Установка: @@ -1250,49 +1249,6 @@ $ rm -rf ~/.config/google-chrome # Справка по командам и т.д. ## [Cheat.sh](https://github.com/chubin/cheat.sh) Ищет на stackoverflow и других ресурсах справку по командам и языкам программирования. @@ -1342,6 +1298,64 @@ os.OpenFile(name, os.O_RDONLY|os.O_CREATE, 0666) // [JimB] [so/q/35558787] [cc by-sa 3.0] ``` ## [Marker](https://github.com/pindexis/marker) Установка: ```bash $ git clone --depth=1 https://github.com/pindexis/marker ~/.marker && ~/.marker/install.py ``` * Ctrl-space: search for commands that match the current written string in the command-line. * Ctrl-k (or marker mark): Bookmark a command. * Ctrl-t: place the cursor at the next placeholder, identified by '{{anything}}' * marker remove: remove a bookmark ## [TLDR](https://github.com/tldr-pages/tldr) Этим я пользовался до cht.sh. ```bash $ npm i tldr -g ``` Получаем краткую справку по команде: ```bash $ tldr nvm ✔ Page not found. Updating cache... ✔ Creating index... nvm Install, uninstall or switch between Node.js versions. Supports version numbers like "0.12" or "v4.2", and labels like "stable", "system", etc. Homepage: https://github.com/creationix/nvm. - Install a specific version of Node.js: nvm install node_version - Use a specific version of Node.js in the current shell: nvm use node_version - Set the default Node.js version: nvm alias default node_version - List all available Node.js versions and highlight the default one: nvm list - Uninstall a given Node.js version: nvm uninstall node_version - Launch the REPL of a specific version of Node.js: nvm run node_version --version - Execute a script in a specific version of Node.js: nvm exec node_version node app.js ``` # Шпаргалка по командам Shell ```bash -
s3rgeym revised this gist
Jul 13, 2019 . 2 changed files with 39 additions and 39 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,21 +1,21 @@ # Оглавление 1. [Установка](#установка) 1. [Предисловие](#предисловие) 1. [Создание образа](#создание-образа) 1. [BIOS/UEFI](#biosuefi) 1. [Настройка сети](#настройка-сети) 1. [Разметка диска](#разметка-диска) 1. [Устанавливаем ядро](#устанавливаем-ядро) 1. [Генерируем fstab](#генерируем-fstab) 1. [arch-chroot](#archchroot) 1. [Настраиваем дату и локаль](#настраиваем-дату-и-локаль) 1. [Прописываем хосты](#прописываем-хосты) 1. [Initramfs](#initramfs) 1. [Ставим пакеты](#ставим-пакеты) 1. [Пользователи](#пользователи) 1. [Установка grub](#установка-grub) 1. [Завершение](#завершение) 1. [Пакетные менеджеры](#пакетные-менеджеры) 1. [Нужные пакеты](#нужные-пакеты) 1. [Масштабировавние 150% как в Windows](#масштабировавние-150-как-в-windows) @@ -29,22 +29,22 @@ 1. [Добавляем путь в PATH](#добавляем-путь-в-path) 1. [bin в домашнем каталоге](#bin-в-домашнем-каталоге) 1. [ZSH](#zsh) 1. [Установка](#установка) 1. [Oh My Zsh](#oh-my-zsh) 1. [Темы](#темы) 1. [Jovial](#jovial) 1. [Powerlevel10k](#powerlevel10k) 1. [Ссылки](#ссылки) 1. [cat с цветной подсветкой](#cat-с-цветной-подсветкой) 1. [Цветовые схемы для терминала](#цветовые-схемы-для-терминала) 1. [Блокируем сайты с рекламой через hosts](#блокируем-сайты-с-рекламой-через-hosts) 1. [asdf-vm](#asdfvm) 1. [Установка:](#установка) 1. [Git](#git) 1. [AUR](#aur) 1. [Удаление](#удаление) 1. [Примеры](#примеры) 1. [Ссылки](#ссылки) 1. [Использование NVM](#использование-nvm) 1. [Настройка Docker](#настройка-docker) 1. [Настройка Visual Code](#настройка-visual-code) @@ -57,19 +57,19 @@ 1. [Блокировка рекламных сайтов](#блокировка-рекламных-сайтов) 1. [Редактирование DConf](#редактирование-dconf) 1. [i3](#i3) 1. [Описание](#описание) 1. [Установка и настройка](#установка-и-настройка) 1. [XTerm](#xterm) 1. [Termite: горячие клавиши](#termite-горячие-клавиши) 1. [Цветовые схемы Termite](#цветовые-схемы-termite) 1. [Заставка lockscreen](#заставка-lockscreen) 1. [Сохранение/восстановление рабочего пространства](#сохранениевосстановление-рабочего-пространства) 1. [Частые проблемы](#частые-проблемы) 1. [Что делать, если каталоги открываются в VSCode?](#что-делать-если-каталоги-открываются-в-vscode) 1. [Enter password to unlock your login keyring](#enter-password-to-unlock-your-login-keyring) 1. [Справка по командам и т.д.](#справка-по-командам-и-тд) 1. [TLDR](#tldr) 1. [Cheat.sh](#cheatsh) 1. [Шпаргалка по командам Shell](#шпаргалка-по-командам-shell) # Установка This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -23,4 +23,4 @@ uri = re.sub(r'[^\w\s]', '', uri) # Заменяем пробелы на «-» uri = uri.replace(' ', '-') print(' ' * (depth - 1) + f'1. [{name}](#{uri})') -
s3rgeym revised this gist
Jul 13, 2019 . 2 changed files with 105 additions and 13 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,3 +1,77 @@ # Оглавление 1. [Установка](#установка) 1. [Предисловие](#предисловие) 1. [Создание образа](#создание-образа) 1. [BIOS/UEFI](#biosuefi) 1. [Настройка сети](#настройка-сети) 1. [Разметка диска](#разметка-диска) 1. [Устанавливаем ядро](#устанавливаем-ядро) 1. [Генерируем fstab](#генерируем-fstab) 1. [arch-chroot](#archchroot) 1. [Настраиваем дату и локаль](#настраиваем-дату-и-локаль) 1. [Прописываем хосты](#прописываем-хосты) 1. [Initramfs](#initramfs) 1. [Ставим пакеты](#ставим-пакеты) 1. [Пользователи](#пользователи) 1. [Установка grub](#установка-grub) 1. [Завершение](#завершение) 1. [Пакетные менеджеры](#пакетные-менеджеры) 1. [Нужные пакеты](#нужные-пакеты) 1. [Масштабировавние 150% как в Windows](#масштабировавние-150-как-в-windows) 1. [Расширения для Gnome](#расширения-для-gnome) 1. [Заменяем ядро на стабильное](#заменяем-ядро-на-стабильное) 1. [Пользовательские сочетания клавиш](#пользовательские-сочетания-клавиш) 1. [Шрифты](#шрифты) 1. [Запуск исполняемых файлов по двойному клику в Nautilus](#запуск-исполняемых-файлов-по-двойному-клику-в-nautilus) 1. [Шаблоны файлов](#шаблоны-файлов) 1. [Права](#права) 1. [Добавляем путь в PATH](#добавляем-путь-в-path) 1. [bin в домашнем каталоге](#bin-в-домашнем-каталоге) 1. [ZSH](#zsh) 1. [Установка](#установка) 1. [Oh My Zsh](#oh-my-zsh) 1. [Темы](#темы) 1. [Jovial](#jovial) 1. [Powerlevel10k](#powerlevel10k) 1. [Ссылки](#ссылки) 1. [cat с цветной подсветкой](#cat-с-цветной-подсветкой) 1. [Цветовые схемы для терминала](#цветовые-схемы-для-терминала) 1. [Блокируем сайты с рекламой через hosts](#блокируем-сайты-с-рекламой-через-hosts) 1. [asdf-vm](#asdfvm) 1. [Установка:](#установка) 1. [Git](#git) 1. [AUR](#aur) 1. [Удаление](#удаление) 1. [Примеры](#примеры) 1. [Ссылки](#ссылки) 1. [Использование NVM](#использование-nvm) 1. [Настройка Docker](#настройка-docker) 1. [Настройка Visual Code](#настройка-visual-code) 1. [Гибернация](#гибернация) 1. [RAID](#raid) 1. [Установка и настройка Postgres](#установка-и-настройка-postgres) 1. [Работаем с github через ssh](#работаем-с-github-через-ssh) 1. [Tor Service](#tor-service) 1. [Emoji](#emoji) 1. [Блокировка рекламных сайтов](#блокировка-рекламных-сайтов) 1. [Редактирование DConf](#редактирование-dconf) 1. [i3](#i3) 1. [Описание](#описание) 1. [Установка и настройка](#установка-и-настройка) 1. [XTerm](#xterm) 1. [Termite: горячие клавиши](#termite-горячие-клавиши) 1. [Цветовые схемы Termite](#цветовые-схемы-termite) 1. [Заставка lockscreen](#заставка-lockscreen) 1. [Сохранение/восстановление рабочего пространства](#сохранениевосстановление-рабочего-пространства) 1. [Частые проблемы](#частые-проблемы) 1. [Что делать, если каталоги открываются в VSCode?](#что-делать-если-каталоги-открываются-в-vscode) 1. [Enter password to unlock your login keyring](#enter-password-to-unlock-your-login-keyring) 1. [Справка по командам и т.д.](#справка-по-командам-и-тд) 1. [TLDR](#tldr) 1. [Cheat.sh](#cheatsh) 1. [Шпаргалка по командам Shell](#шпаргалка-по-командам-shell) # Установка ## Предисловие @@ -8,7 +82,7 @@ ## Создание образа Качаем [образ](https://www.archlinux.org/download/) и записываем его с помощью команды: ```bash $ sudo dd if=/path/to/iso of=/dev/sdX bs=8M status=progress; sync @@ -21,7 +95,7 @@ $ sudo dd if=/path/to/iso of=/dev/sdX bs=8M status=progress; sync   ## BIOS/UEFI При загрузке системы нажимаем F2 или Del (зависит от производителя материнской платы). Во вкладке BIOS в приоритете загрузки делаем первым наше USB-устройство. Нажимаем F10 и сохраняем настройки. @@ -173,7 +247,7 @@ mkinitcpio -p linux Эти пакеты понадобятся далее: ```bash pacman -S sudo grub efibootmgr ntfs-3g os-prober alsa-utils xf86-video-ati gnome ``` xf86-video-ati – свободный драйвер для видеокарт AMD. xorg и xorg-server отдельно ставить не нужно, так как эти пакеты есть в зависимостях. @@ -338,15 +412,7 @@ yay -Sy linux-headers \ # нужны для компиляции некотор xclip # копирование файла в буффер обмена из консоли ``` # Масштабировавние 150% как в Windows По-умолчанию в Gnome масштабирование кратно 100. Чтобы добавить варианты масштабирования 125% и 150% нужно выполнить в терминале: @@ -360,7 +426,7 @@ gsettings set org.gnome.mutter experimental-features "['scale-monitor-framebuffe gsettings reset org.gnome.mutter experimental-features ``` # Расширения для Gnome Устанавливаем [расширение](https://chrome.google.com/webstore/detail/gnome-shell-integration/gphhapmejobijbbhgpjhcjognlahblep?hl=ru) для Chrome. This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,26 @@ #!/usr/bin/env python from pathlib import Path import re base_path = Path(__file__).resolve().parent with (base_path / 'Arch-Instruction.md').open() as fp: contents = fp.read() # Сначала нормализуем контент, удаляя все вставки кода contents = re.sub(r'```.*?```', '', contents, flags=re.S) # Теперь ищем заголовки headers = re.findall('^#.*', contents, re.M) for header in headers: l = len(header) name = header.lstrip('#') depth = len(header) - len(name) name = name.strip() # Теперь вырезаем ссылки name = re.sub(r'\[(.*?)\]\(.*?\)', r'\1', name) uri = name.lower() # Вырезаем все не буквенно-цифровые символы uri = re.sub(r'[^\w\s]', '', uri) # Заменяем пробелы на «-» uri = uri.replace(' ', '-') print(' ' * (depth - 1) + f'1. [{name}](#{uri})') -
s3rgeym revised this gist
Jul 13, 2019 . 1 changed file with 4 additions and 2 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -483,7 +483,7 @@ export PATH=/path/to/bin:$PATH mkdir ~/bin echo 'export PATH=$HOME/bin:$PATH' >> ~/.zprofile # or echo 'export PATH=$HOME/bin:$PATH' >> ~/.zshrc ``` Теперь самописные скрипты можно кидать в `~/bin`, так они будут доступны только для текущего пользователя. @@ -586,7 +586,7 @@ source $ZSH/oh-my-zsh.sh ```bash # Сначала сохраняем копию zhsrc, потому как jovial изменить оригинальеный файл $ cp ~/.zshrc ~/.zshrc.bak $ curl -sSL git.io/jovial | sudo bash -s $USER ``` @@ -736,6 +736,8 @@ sqlite # Использование [NVM](https://github.com/nvm-sh/nvm) > ⚠️ Использование [asdf-vm](#asdf-vm) предпочительнее. Устанавливаем последнюю версию Node.js: ```bash -
s3rgeym revised this gist
Jul 13, 2019 . 1 changed file with 117 additions and 105 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -4,6 +4,8 @@ ***Arch Linux*** ‒ это один из немногих дистрибутивов Linux, использующих модель роллинг-релизов. Это означает, что в нем доступны самые последние версии пакетов. Это одновременно является его как преимуществом так и недостатком. Пересесть на него меня заставила необходимость: мое компьютерное железо (процессор ryzen 5 2600 и видеоадаптер rx 590) оказались не совместимы с версией Linux Kernel младше 4.20.  ## Создание образа Качаем образ с сайта и записываем его с помощью команды: @@ -400,7 +402,7 @@ mkinitcpio -p linux Шрифты надо кидать в `/usr/share/fonts` либо в `~/.fonts` или в `~/.local/share/fonts`. После выполняем: ```bash $ fc-cache -f -v # Чтобы проверить установлен ли шрифт @@ -548,7 +550,7 @@ yay -S powerline-fonts Ставим must-have плагины: ```bash git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions git clone https://github.com/zsh-users/zsh-completions ${ZSH_CUSTOM:=~/.oh-my-zsh/custom}/plugins/zsh-completions git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting @@ -594,19 +596,19 @@ $ curl -sSL git.io/jovial | sudo bash -s $USER Это красивая тема для ZSH. ```bash git clone https://github.com/romkatv/powerlevel10k.git $ZSH_CUSTOM/themes/powerlevel10k ``` `~/.zshrc`: ```bash ZSH_THEME=powerlevel10k/powerlevel10k ``` Изменим prompt: ```bash cd && curl -fsSLO https://raw.githubusercontent.com/romkatv/dotfiles-public/master/.purepower echo 'source ~/.purepower' >>! ~/.zshrc ``` @@ -664,14 +666,14 @@ yay -S asdf-vm В `~/.zshrc` (после compinit) добавляем строки: ```bash . /opt/asdf-vm/asdf.sh . /opt/asdf-vm/completions/asdf.bash ``` В `~/.zprofile`: ```bash export PATH=/opt/asdf-vm/bin:$PATH ``` @@ -1231,15 +1233,15 @@ $ tldr nvm ```bash curl https://cht.sh/:cht.sh | sudo tee /usr/local/bin/cht.sh sudo chmod +x /usr/local/bin/cht.sh # Так же требуются пакеты xsel и rlwrap yay -S xsel rlwrap ``` Использование: ```bash # Интерактивный режим $ cht.sh --shell <language> $ cht.sh --shell bash @@ -1353,6 +1355,110 @@ x=${x:-default} # Экспорт глобальной переменной export VAR=42 # Генерация строк с помощью Brace expansion $ echo a{d,c,b}e ade ace abe # Массивы arr=(Hello World) echo ${arr[0]} ${arr[1]} ${arr[*]} # Все записи в массиве ${!arr[*]} # Все индексы в массиве ${#arr[*]} # Количество записей в массиве ${#arr[0]} # Длина первой записи (нумерация с нуля) array=(one two three four [5]=five) echo "Array size: ${#array[*]}" # Выводим размер массива echo "Array items:" # Выводим записи массива for item in ${array[*]} do printf " %s\n" $item done echo "Array indexes:" # Выводим индексы массива for index in ${!array[*]} do printf " %d\n" $index done echo "Array items and indexes:" # Выводим записи массива с их индексами for index in ${!array[*]} do printf "%4d: %s\n" $index ${array[$index]} done # Следующий пример покажет, как кавычки и конструкции без кавычек возвращают строки (особенно важно, когда в этих строках есть пробелы): array=("first item" "second item" "third" "item") echo "Number of items in original array: ${#array[*]}" for ix in ${!array[*]} do printf " %s\n" "${array[$ix]}" done echo arr=(${array[*]}) echo "After unquoted expansion: ${#arr[*]}" for ix in ${!arr[*]} do printf " %s\n" "${arr[$ix]}" done echo arr=("${array[*]}") echo "After * quoted expansion: ${#arr[*]}" for ix in ${!arr[*]} do printf " %s\n" "${arr[$ix]}" done echo arr=("${array[@]}") echo "After @ quoted expansion: ${#arr[*]}" for ix in ${!arr[*]} do printf " %s\n" "${arr[$ix]}" done # Циклы for i in $(seq 1 10); do echo $i done for ((i = 0 ; i < max ; i++ )) do echo $i done for i in {0..10} do echo $i done for w in word1 word2 word3 do doSomething($w) done i=0 while (( ++i <= num )); do printf 'counter is at %d\n' "$i" done i=1 while [ "$i" -le "$num" ]; do printf 'counter is at %d\n' "$i" i=$(( i + 1 )) done # Условия if [ "$seconds" -eq 0 ]; then @@ -1447,100 +1553,6 @@ case $VAR in *) ... ;; esac # Объявление функции foo() { # Аргументы функции @@ -1570,7 +1582,7 @@ echo "Today is $(date). A fine day." # Направить stdout одной программы в stdin другой command1 | command2 # Перенаправление stdout и stderr command1 |& command2 # Создать либо перезаписать файл, добавив строку @@ -1924,7 +1936,7 @@ $ git add . # Закоммитить изменения (сделать описание) $ git commit -m "Тест" # Если не были добавлены новые файлы, а лишь производились изменения в уже добавленных, то можно использовать только одну команду $ git commit -am "Тест" # Обновить репозиторий на сервере -
s3rgeym revised this gist
Jul 13, 2019 . 1 changed file with 17 additions and 7 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -2,7 +2,7 @@ ## Предисловие ***Arch Linux*** ‒ это один из немногих дистрибутивов Linux, использующих модель роллинг-релизов. Это означает, что в нем доступны самые последние версии пакетов. Это одновременно является его как преимуществом так и недостатком. Пересесть на него меня заставила необходимость: мое компьютерное железо (процессор ryzen 5 2600 и видеоадаптер rx 590) оказались не совместимы с версией Linux Kernel младше 4.20. ## Создание образа @@ -50,7 +50,7 @@ fdisk /dev/nvme0n1 В меню fdisk вводим `n` для создания нового раздела, порядковый номер раздела, потом начальное и конечные смещения. При задании конечного смещения можно отрицательное значение, например, `-10G`, так мы оставим свободными 10 Гб в конце диска. Для записи изменений на жесткий диск вводим `w` и выходим - `q`. Теперь нужно разметить раздел по LVM. Касательно LVM: единственное удобство в нем для меня – это возможность динамически менять размер каталогов. Самая частая проблема, которая у меня была раньше – это то, что я не угадывал размер для корня. Когда в нем кончалось место, я с установочной флешки через gparted пытался отщепнуть от виндового раздела кусок (а у меня разделы всегда шли так: recovery, efi, reserved, windows, root, home), из этого куска создавал временный раздел, копировал в него файлы с хомяка, удалял хомяка, изменял размер корневого, опять создавал хомяка и из временного раздела копировал в него файлы, потом удалял временный раздел, расширял виндовый, правил `/etc/fstab`… А с LVM я могу просто выполнить пару команд: ужать хомяка, увеличить корневой, причем, на лету. Но эксперты могут возразить: «Хомяк на отдельном разделе не нужен!» — Да, если хочешь потерять все данные при переустановке. Создадим группу: @@ -414,7 +414,7 @@ $ fc-list | grep "<name-of-font>" * [Powrline Fonts](https://github.com/powerline/fonts); * [Nerd Fonts](https://github.com/ryanoasis/nerd-fonts). # Запуск исполняемых файлов по двойному клику в Nautilus Заставляем Nautilus выполнять исполняемые файлы вместо открытия их в текстовом редакторе. Нужно нажать на три точки, а потом выбрать Preferences: @@ -578,15 +578,19 @@ source $ZSH/oh-my-zsh.sh * [Встроенные темы](https://github.com/robbyrussell/oh-my-zsh/wiki/Themes); * [Сторонние темы](https://github.com/robbyrussell/oh-my-zsh/wiki/External-themes). ## Темы ### [Jovial](https://github.com/zthxxx/jovial) ```bash # Сначала сохраняем копию zhsrc, потому как jovial изменить оригинальеный файл $ cp ~/.zshrc ~/.zhrc.bak $ curl -sSL git.io/jovial | sudo bash -s $USER ``` У меня эта тема упорно устанавливается в `/root/.oh-my-zsh`. ### [Powerlevel10k](https://github.com/romkatv/powerlevel10k) Это красивая тема для ZSH. @@ -1590,7 +1594,7 @@ EOF # ============================================================================== # # Написание скриптов # # ============================================================================== @@ -1737,10 +1741,16 @@ $ mkdir <target> # Создание каталога вместе с родительскими каталогами, если тех не существует $ mkdir -p <target> # Создать каталог с определенными правами $ mkdir -m 0750 <directory> # Создание множества каталогов $ mkdir foo bar baz # или $ mkdir prefix-{foo,bar,baz} # Такой же трюк работает при создании файлов $ touch {foo,bar,baz}.txt # Создать мягкую ссылку на файл либо заменить ее новой $ ln -sf path/to/new_file path/to/symlink -
s3rgeym renamed this gist
Jul 13, 2019 . 1 changed file with 122 additions and 118 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -255,13 +255,7 @@ reboot --- # Пакетные менеджеры Пакетным менеджером по-умолчанию для Arch Linux является pacman. Для подсветки вывода pacman в `/etc/pacman.conf` нужно раскомментировать `Color`. Пользовательским репозиторием является [AUR](https://aur.archlinux.org/). Пакеты из него можно использовать только на свой страх и риск. Чтобы не собирать пакеты из него ручками можно поставить yay: @@ -283,7 +277,7 @@ makepkg -si * [Сравнеие пакетных менеджеров](https://wiki.archlinux.org/index.php/AUR_helpers_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)). # Нужные пакеты Это список необходимых для меня пакетов: @@ -348,6 +342,8 @@ yay -Sy linux-headers \ # нужны для компиляции некотор yay -Rns epiphany ``` # Gnome ## Масштабировавние 150% как в Windows По-умолчанию в Gnome масштабирование кратно 100. Чтобы добавить варианты масштабирования 125% и 150% нужно выполнить в терминале: @@ -362,7 +358,27 @@ gsettings set org.gnome.mutter experimental-features "['scale-monitor-framebuffe gsettings reset org.gnome.mutter experimental-features ``` ## Расширения для Gnome Устанавливаем [расширение](https://chrome.google.com/webstore/detail/gnome-shell-integration/gphhapmejobijbbhgpjhcjognlahblep?hl=ru) для Chrome.  Управление расширениями осуществляется через Tweaks.  Расширения для установки: | Название <img width="450"> | Описание <img width="450"> | | -- | -- | | [Dash to Dock](https://extensions.gnome.org/extension/307/dash-to-dock/). | Выезжающий Dash - панель с избранными приложениями | | [Desktop Icons](https://extensions.gnome.org/extension/1465/desktop-icons/) | Иконки на рабочем столе | | [ShellTile](https://extensions.gnome.org/extension/657/shelltile/) | Тайловый менеджер | | [Log Out Button](https://extensions.gnome.org/extension/1143/logout-button/) | Добавляет кнопку, которая выполняет выход из системы | # Заменяем ядро на стабильное Если надоело, что что-то ломается почти после каждого обновления ядра, запускаем терминал и выполняем: @@ -372,15 +388,15 @@ yay -R linux linux-headers mkinitcpio -p linux ``` # Пользовательские сочетания клавиш В Settings → Devices → Keyboard добавляем сочетания клавиш: * `Ctrl + Alt + T` для запуска терминала (`gnome-terminal`); * `Ctrl + Alt + V` для запуска Visual Code (`code`).  # Шрифты Шрифты надо кидать в `/usr/share/fonts` либо в `~/.fonts` или в `~/.local/share/fonts`. После выполняем: @@ -398,21 +414,21 @@ $ fc-list | grep "<name-of-font>" * [Powrline Fonts](https://github.com/powerline/fonts); * [Nerd Fonts](https://github.com/ryanoasis/nerd-fonts). # Запуск исполняемых файлов по двойному клику Заставляем Nautilus выполнять исполняемые файлы вместо открытия их в текстовом редакторе. Нужно нажать на три точки, а потом выбрать Preferences:  # Шаблоны файлов Чтобы в Nautilus в контекстном меню отображался пункт `New Document`, нужно в `~/Templaytes` создать шаблоны файлов: ```bash touch ~/Templates/{Empty\ Document,Text\ Document.txt,README.md,pyfile.py} ``` # Права 4 - Чтение (r) 2 - Запись (w) @@ -449,7 +465,7 @@ d | rwx | r-x | r-x * [Права доступа к файлам и каталогам](https://www.linuxcenter.ru/lib/books/kostromin/gl_04_05.phtml) # Добавляем путь в PATH * Bash Shell: `~.bash_profile`, `~/.bashrc` or `~/.profile` * Korn Shell: `~/.kshrc` or `~/.profile` @@ -459,7 +475,7 @@ d | rwx | r-x | r-x export PATH=/path/to/bin:$PATH ``` # bin в домашнем каталоге ```bash mkdir ~/bin @@ -496,29 +512,9 @@ $ hello $USER Hello, sergey! ``` # ZSH ## Установка ```bash $ yay -S zsh @@ -534,7 +530,7 @@ $ chsh -s $(which zsh) ## [Oh My Zsh](https://github.com/robbyrussell/oh-my-zsh) Установка: @@ -582,15 +578,15 @@ source $ZSH/oh-my-zsh.sh * [Встроенные темы](https://github.com/robbyrussell/oh-my-zsh/wiki/Themes); * [Сторонние темы](https://github.com/robbyrussell/oh-my-zsh/wiki/External-themes). Из сторонних тем наиболее симпатична [jovial](https://github.com/zthxxx/jovial). ```bash # Сначала сохраняем копию zhsrc, потому как jovial изменить оригинальеный файл $ cp ~/.zshrc ~/.zhrc.bak $ curl -sSL git.io/jovial | sudo bash -s $USER ``` ## [Powerlevel10k](https://github.com/romkatv/powerlevel10k) Это красивая тема для ZSH. @@ -613,16 +609,16 @@ echo 'source ~/.purepower' >>! ~/.zshrc  ## Ссылки * [Приемы при работе с ZSH](http://zzapper.co.uk/zshtips.html). # cat с цветной подсветкой * [ccat](https://github.com/jingweno/ccat); * [lolcat](https://github.com/busyloop/lolcat). # [Цветовые схемы для терминала](https://github.com/Mayccoll/Gogh) ```bash # Интерактивная установка @@ -635,17 +631,17 @@ dconf reset -f /org/gnome/terminal/legacy/profiles:/ * [Обзор тем](https://mayccoll.github.io/Gogh/). # Блокируем сайты с рекламой через hosts ```bash wget -qO- https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts | sudo tee --append /etc/hosts ``` # [asdf-vm](https://github.com/asdf-vm/asdf) ## Установка: ## Git ```bash git clone https://github.com/asdf-vm/asdf.git ~/.asdf @@ -656,7 +652,7 @@ echo -e '\n. $HOME/.asdf/asdf.sh' >> ~/.zshrc echo -e '\n. $HOME/.asdf/completions/asdf.bash' >> ~/.zshrc ``` ## AUR ```bash yay -S asdf-vm @@ -677,13 +673,13 @@ export PATH=/opt/asdf-vm/bin:$PATH Эту строку можно и в `~/.zshrc`. ## Удаление ```bash rm -rf ~/.asdf/ ~/.tool-versions ``` ## Примеры ```bash $ asdf plugin-add python @@ -708,7 +704,7 @@ $ which node /home/sergey/.asdf/shims/node $ which npm /home/sergey/.asdf/shims/npm $ asdf list golang 1.12 nodejs @@ -728,62 +724,19 @@ sqlite После установки через pip пакетов, которые добавляют команды, чтобы те были доступны, нужно всегда выполнять `asdf reshim python`. ## Ссылки * [Документация](https://asdf-vm.com/#/core-manage-asdf-vm). # Использование [NVM](https://github.com/nvm-sh/nvm) Устанавливаем последнюю версию Node.js: ```bash nvm install node ``` # Настройка Docker ```bash sudo systemctl start docker @@ -801,7 +754,7 @@ docker run hello-world [Ссылка](https://docs.docker.com/install/linux/linux-postinstall/). # Настройка Visual Code ```json { @@ -822,7 +775,7 @@ docker run hello-world } ``` # Гибернация Режим гибернациии от режима сна отличается тем, что в первом случае содержимое оперативной памяти сохраняется на жесткий диск и питание полностью отключается, во втором - питание подается только на оперативку. Чем хороша гибернация? - Например, мы работаем в Linux, вошли в режим гибернации, а затем загрузились в Windows и играем. Когда мы в следующий раз загрузимся в Linux, то увидим все то, что было перед выключением. Прекрасно?! Но часто ли такое нужно? @@ -863,7 +816,7 @@ systemctl hibernate   # RAID В Linux RAID на аппаратном уровне называют FakeRAID. Для работы с FakeRAID используется пакет dmraid. @@ -885,7 +838,7 @@ HOOKS=(base udev autodetect modconf block lvm2 dmraid filesystems keyboard fsck) sudo mkinitcpio -p linux ``` # Установка и настройка Postgres ```bash [sergey@sergey-pc ~]$ sudo pacman -S postgresql @@ -915,7 +868,7 @@ Type "help" for help. sergey=> ``` # Работаем с github через ssh Генерация нового ключа: @@ -949,7 +902,7 @@ git config user.email "[email protected]" git config user.name "codedumps" ``` # Tor Service Включаем Tor: @@ -967,19 +920,19 @@ $ torify curl http://httpbin.org/ip } ``` # Emoji ```yay yay -S ttf-emojione ``` # Блокировка рекламных сайтов ```bash wget -qO- https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts | sudo tee --append /etc/hosts ``` # Редактирование DConf DConf хранит профили терминала в `~/.config/dconf/user`, в формате GVDB [пруф](https://en.wikipedia.org/wiki/Dconf). @@ -1221,9 +1174,54 @@ $ rm -rf ~/.config/google-chrome Теперь остается только перезапустить Chrome. # Справка по командам и т.д. ## [TLDR](https://github.com/tldr-pages/tldr) ```bash npm i tldr -g ``` Получаем краткую справку по команде: ```bash $ tldr nvm ✔ Page not found. Updating cache... ✔ Creating index... nvm Install, uninstall or switch between Node.js versions. Supports version numbers like "0.12" or "v4.2", and labels like "stable", "system", etc. Homepage: https://github.com/creationix/nvm. - Install a specific version of Node.js: nvm install node_version - Use a specific version of Node.js in the current shell: nvm use node_version - Set the default Node.js version: nvm alias default node_version - List all available Node.js versions and highlight the default one: nvm list - Uninstall a given Node.js version: nvm uninstall node_version - Launch the REPL of a specific version of Node.js: nvm run node_version --version - Execute a script in a specific version of Node.js: nvm exec node_version node app.js ``` ## [Cheat.sh](https://github.com/chubin/cheat.sh) Ищет на stackoverflow и других ресурсах справку по командам и языкам программирования. Установка: @@ -1232,19 +1230,19 @@ curl https://cht.sh/:cht.sh | sudo tee /usr/local/bin/cht.sh chmod +x /usr/local/bin/cht.sh # Так же требуются пакеты xsel и rlwrap yay -S xsel rlwrap ``` Использование: ``` # Интерактивный режим $ cht.sh --shell <language> $ cht.sh --shell bash type 'help' for the cht.sh shell help cht.sh/bash> for # shell - Bash 'for' loop syntax? # # Replace for (($i=0... @@ -1259,7 +1257,7 @@ cht.sh/bash> $ cht.sh go create file /* * go - Create an empty text file * * Don't try to check the existence first, since you then have a race if * the file is created at the same time. You can open the file with the * O_CREATE flag to create it if it doesn't exist: @@ -1436,8 +1434,7 @@ man [ # Строка слева всегда имя переменной x=42; [[ "x" -eq "42" ]] || echo fail # выражение слева всегда переменная case $VAR in foo) ... ;; @@ -1645,7 +1642,7 @@ $ yay -Y --gendb # Ошибки с удалением зависимостей $ yay -Rns gnome-extra checking dependencies... error: failed to prepare transaction (could not satisfy dependencies) :: nautilus: removing nautilus-sendto breaks dependency 'nautilus-sendto' @@ -1713,13 +1710,20 @@ $ mv <src> <dst> # Копирование файлов $ cp <src> <dst> # Копировать каталог и все вложенные файлы $ cp -r <src> <dst> # Полный путь до файла $ realpath example.txt /home/username/example.txt # Листинг каталога $ ls $ tldr ls # Вывести информацию о владельце и группе файла $ ls -ld /path/to/file $ stat /path/to/file # Вывести все вложенные файлы $ ls -R <path> @@ -1910,7 +1914,7 @@ $ git add . # Закоммитить изменения (сделать описание) $ git commit -m "Тест" # Добавляет модифицированные файлы (новые не добавляет) и делает коммит $ git commit -am "Тест" # Обновить репозиторий на сервере -
s3rgeym revised this gist
Jul 12, 2019 . 1 changed file with 5 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1785,6 +1785,9 @@ $ df -h --total # Узнать на каком разделе смонтирован каталог $ df -h /tmp # Просмотр числа inode $ df -i # Просмотр содержимого фйала с навигацией $ less /path/to/file @@ -2057,5 +2060,7 @@ $ htop * [Цвет и форматирование текста в консоли](https://misc.flogisoft.com/bash/tip_colors_and_formatting); * [Поиск файлов на Сервере](https://www.8host.com/blog/ispolzovanie-find-i-locate-dlya-poiska-fajlov-na-servere-linux/); * [Файловая система Linux](https://opencentr.ru/article/fajlovaya-sistema-linux/); * [Inode](https://ru.wikipedia.org/wiki/Inode); * [Управление разделами LVM](https://web.mit.edu/rhel-doc/5/RHEL-5-manual/Deployment_Guide-en-US/s1-disk-storage-lvm.html); * [Часто используемые команды Git](https://carolinegabriel.com/used-git-commands-copy-paste-format/). -
s3rgeym revised this gist
Jul 12, 2019 . 1 changed file with 9 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1705,9 +1705,18 @@ LOWERCASE # Список разделов $ sudo fdisk -l # В Linux все файлы. Регулярные файлы ‒ обычные файлы, каталоги ‒ это файлы содержащие список файлов и т.д. # Перемещение/переименование файла $ mv <src> <dst> # Копирование файлов $ cp <src> <dst> # Полный путь до файла $ realpath example.txt /home/username/example.txt # Листинг каталога $ ls $ tldr ls -
s3rgeym revised this gist
Jul 12, 2019 . 1 changed file with 12 additions and 6 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1351,9 +1351,6 @@ x=${x:-default} # Экспорт глобальной переменной export VAR=42 # Условия if [ "$seconds" -eq 0 ]; then @@ -1607,6 +1604,18 @@ EOF # Так же часто делают каталог скрипта рабочим (по-умолчанию рабочим является тот откуда запустили скрипт) cd "$(dirname "$0")" # ============================================================================== # # Выполнение скриптов # # ============================================================================== # Сделать файл исполняемым $ chmod +x /path/to/file # Выполнит скрипт в текущем процессе (переменные и функции, объявленные внутри скрипта станут доступны в терминале) $ source /path/to/file # ============================================================================== # # Пакеты @@ -1696,9 +1705,6 @@ LOWERCASE # Список разделов $ sudo fdisk -l # Перемещение/переименование файла $ mv <src> <dst> -
s3rgeym revised this gist
Jul 12, 2019 . 1 changed file with 8 additions and 6 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -544,12 +544,6 @@ sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/mas Пакет из репозитория ставится вне домашнего каталога, а потому требует root права при установке плагинов, что не удобно. Так же для некоторых тем Oh My Zsh нужны шрифты наподобие Powerline: ```bash @@ -588,6 +582,14 @@ source $ZSH/oh-my-zsh.sh * [Встроенные темы](https://github.com/robbyrussell/oh-my-zsh/wiki/Themes); * [Сторонние темы](https://github.com/robbyrussell/oh-my-zsh/wiki/External-themes). Из сторонних тем наиболее симпатична [jovial](https://github.com/zthxxx/jovial). ```bash # Сначала сохраняем копию zhsrc, потому как jovial изменить оригинальеный файл $ cp ~/.zshrc ~/.zhrc.bak $ curl -sSL git.io/jovial | sudo bash -s $USER ``` ### [Powerlevel10k](https://github.com/romkatv/powerlevel10k) Это красивая тема для ZSH. -
s3rgeym revised this gist
Jul 12, 2019 . 1 changed file with 18 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1228,13 +1228,31 @@ $ rm -rf ~/.config/google-chrome ```bash curl https://cht.sh/:cht.sh | sudo tee /usr/local/bin/cht.sh chmod +x /usr/local/bin/cht.sh # Так же требуются пакеты xsel и rlwrap yay -S xsel lwrap ``` Использование: ``` # Интерактивный режим $ cht.sh --shell <language> $ cht.sh --shell bash type 'help' for the cht.sh shell help cht.sh/bash> for # shell - Bash 'for' loop syntax? # # Replace for (($i=0... # with for ((i=0;i<10;i++)) # [jman] [so/q/6854118] [cc by-sa 3.0] cht.sh/bash> $ cht.sh go create file /* -
s3rgeym revised this gist
Jul 12, 2019 . 1 changed file with 4 additions and 4 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1569,10 +1569,10 @@ command1 <<< command2 # Вывод многострочного текста cat <<EOF хуй пизда джигурда EOF # ============================================================================== # -
s3rgeym revised this gist
Jul 12, 2019 . 1 changed file with 31 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1219,6 +1219,37 @@ $ rm -rf ~/.config/google-chrome Теперь остается только перезапустить Chrome. # [Cheat.sh](https://github.com/chubin/cheat.sh) Ищет на stackoverflow и других ресурсах справку по языкам программирования Установка: ```bash curl https://cht.sh/:cht.sh | sudo tee /usr/local/bin/cht.sh chmod +x /usr/local/bin/cht.sh ``` Использование: ``` # Интерактивный режим $ cht.sh --shell <language> $ cht.sh go create file /* * go - Create an empty text file * * Don't try to check the existence first, since you then have a race if * the file is created at the same time. You can open the file with the * O_CREATE flag to create it if it doesn't exist: */ os.OpenFile(name, os.O_RDONLY|os.O_CREATE, 0666) // [JimB] [so/q/35558787] [cc by-sa 3.0] ``` # Шпаргалка по командам Shell ```bash -
s3rgeym revised this gist
Jul 12, 2019 . 1 changed file with 4 additions and 1 deletion.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1839,7 +1839,10 @@ $ git merge <branchname> $ git add . # Закоммитить изменения (сделать описание) $ git commit -m "Тест" # Добавляет модифицированные файлы (новые не добавляет) и делает коммит $ git commit -am "Тест" # Обновить репозиторий на сервере $ git push -
s3rgeym revised this gist
Jul 12, 2019 . 1 changed file with 4 additions and 1 deletion.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -585,6 +585,9 @@ source $ZSH/oh-my-zsh.sh Для темы Agnoster настройках терминала выбираем шрифт `Source Code Pro Regular`, чтобы отображались стрелочки. * [Встроенные темы](https://github.com/robbyrussell/oh-my-zsh/wiki/Themes); * [Сторонние темы](https://github.com/robbyrussell/oh-my-zsh/wiki/External-themes). ### [Powerlevel10k](https://github.com/romkatv/powerlevel10k) Это красивая тема для ZSH. @@ -617,7 +620,7 @@ echo 'source ~/.purepower' >>! ~/.zshrc * [ccat](https://github.com/jingweno/ccat); * [lolcat](https://github.com/busyloop/lolcat). ## [Цветовые схемы для терминала](https://github.com/Mayccoll/Gogh) ```bash # Интерактивная установка -
s3rgeym revised this gist
Jul 12, 2019 . 1 changed file with 10 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1648,6 +1648,16 @@ $ chmod +x /path/to/file # Перемещение/переименование файла $ mv <src> <dst> # Листинг каталога $ ls $ tldr ls # Вывести все вложенные файлы $ ls -R <path> $ find <path> -print # Покажет имя и размер $ du -a <path> # Создание каталога $ mkdir <target> -
s3rgeym revised this gist
Jul 12, 2019 . 1 changed file with 12 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -703,6 +703,18 @@ $ which node /home/sergey/.asdf/shims/node $ which npm /home/sergey/.asdf/shims/npm $ asdf list golang 1.12 nodejs 10.16.0 postgres 11.4 python 2.7.15 3.7.3 sqlite 3.29.0 ``` [Все доступные плагины](https://asdf-vm.com/#/plugins-all). При установке, использовании плагинов могут возникать проблемы. Например, плагин для Python работает поверх [pyenv](https://github.com/pyenv/pyenv) и при возникновении проблем, следует изучить страницу [«Common build problems»](https://github.com/pyenv/pyenv/wiki/common-build-problems). -
s3rgeym revised this gist
Jul 12, 2019 . 1 changed file with 3 additions and 1 deletion.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1196,12 +1196,14 @@ $ yay -S seahorse $ rm -rf ~/.local/share/keyrings ``` Далее удаляем настройки Chrome: ```bash $ rm -rf ~/.config/google-chrome ``` Теперь остается только перезапустить Chrome. # Шпаргалка по командам Shell ```bash -
s3rgeym revised this gist
Jul 11, 2019 . 1 changed file with 3 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1728,6 +1728,9 @@ $ sudo lvresize -L +10GB /dev/mapper/lvm-root # После lvresize нужно обязательно изменить размер файловой системы $ sudo resize2fs /dev/mapper/lvm-root # Делает то же самое, что и две команды выше $ sudo lvresize -r -L +10GB /dev/mapper/lvm-root # Список логических разделов LVM $ sudo lvscan ACTIVE '/dev/lvm/root' [40.00 GiB] inherit -
s3rgeym revised this gist
Jul 11, 2019 . 1 changed file with 3 additions and 6 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1338,7 +1338,7 @@ fi # -le # is less than or equal to [ "$a" -le "$b" ] # < # is less than (within double parentheses) @@ -1686,9 +1686,6 @@ Database /var/lib/mlocate/mlocate.db: 119 423 666 bytes in file names 38 722 751 bytes used to store database # Покажет что куда смонтировано (можно свободное место узнать) $ df -h --total @@ -1959,7 +1956,7 @@ $ htop Ссылки: * [Цвет и форматирование текста в консоли](https://misc.flogisoft.com/bash/tip_colors_and_formatting); * [Поиск файлов на Сервере](https://www.8host.com/blog/ispolzovanie-find-i-locate-dlya-poiska-fajlov-na-servere-linux/); * [Управление разделами LVM](https://web.mit.edu/rhel-doc/5/RHEL-5-manual/Deployment_Guide-en-US/s1-disk-storage-lvm.html); * [Часто используемые команды Git](https://carolinegabriel.com/used-git-commands-copy-paste-format/). -
s3rgeym revised this gist
Jul 11, 2019 . 1 changed file with 7 additions and 1 deletion.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1725,13 +1725,19 @@ $ ccat ./file # Вывести файлы в каталоге, отсортировав их по времени до доступа $ ls -ltu <path> # Увеличиваем размер логического раздела $ sudo lvresize -L +10GB /dev/mapper/lvm-root # После lvresize нужно обязательно изменить размер файловой системы $ sudo resize2fs /dev/mapper/lvm-root # Список логических разделов LVM $ sudo lvscan ACTIVE '/dev/lvm/root' [40.00 GiB] inherit ACTIVE '/dev/lvm/home' [20.00 GiB] inherit # Изменить размер каталога /tmp $ mount -o remount,size=4G /tmp/ # Подробная информация о диске $ sudo smartctl -a /dev/nvme0 -
s3rgeym revised this gist
Jul 11, 2019 . 1 changed file with 10 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1566,6 +1566,16 @@ $ yay -Ps # Generates development package DB used for devel updates $ yay -Y --gendb # Ошибки с удалением зависимостей $ yay -Rns gnome-extra checking dependencies... error: failed to prepare transaction (could not satisfy dependencies) :: nautilus: removing nautilus-sendto breaks dependency 'nautilus-sendto' $ yay -Rdd nautilus-sendto # Теперь можно снести gnome-extra # ============================================================================== # # systemd -
s3rgeym revised this gist
Jul 11, 2019 . 1 changed file with 13 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1526,6 +1526,19 @@ cat <<EOF > текст > EOF # ============================================================================== # # Написание скрпитов # # ============================================================================== # Первой строкой скрипта идет Shebang, торый указывает какой интерпретатор использовать #!/usr/bin/env bash # Так же часто делают каталог скрипта рабочим (по-умолчанию рабочим является тот откуда запустили скрипт) cd "$(dirname "$0")" # ============================================================================== # # Пакеты -
s3rgeym revised this gist
Jul 11, 2019 . 1 changed file with 27 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1499,6 +1499,33 @@ die "Kaboom" echo "Today is $(date). A fine day." # Управление выводом # Направить stdout одной программы в stdin другой command1 | command2 # ПЕренаправление и stout и stderr command1 |& command2 # Создать либо перезаписать файл, добавив строку command > out # Создать файл, если его не существует и дописать строку в конец command >> out # Направить stderr команды в файл command 2>&1 out # stdout 2-ой команды, является stdin для первой command1 <<< command2 # Вывод многострочного текста cat <<EOF > Это > многострочный > текст > EOF # ============================================================================== # # Пакеты -
s3rgeym revised this gist
Jul 11, 2019 . 1 changed file with 67 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1408,6 +1408,73 @@ while [ "$i" -le "$num" ]; do i=$(( i + 1 )) done # Массивы arr=(Hello World) echo ${arr[0]} ${arr[1]} ${arr[*]} # Все записи в массиве ${!arr[*]} # Все индексы в массиве ${#arr[*]} # Количество записей в массиве ${#arr[0]} # Длина первой записи (нумерация с нуля) array=(one two three four [5]=five) echo "Array size: ${#array[*]}" # Выводим размер массива echo "Array items:" # Выводим записи массива for item in ${array[*]} do printf " %s\n" $item done echo "Array indexes:" # Выводим индексы массива for index in ${!array[*]} do printf " %d\n" $index done echo "Array items and indexes:" # Выводим записи массива с их индексами for index in ${!array[*]} do printf "%4d: %s\n" $index ${array[$index]} done # Следующий пример покажет, как кавычки и конструкции без кавычек возвращают строки (особенно важно, когда в этих строках есть пробелы): array=("first item" "second item" "third" "item") echo "Number of items in original array: ${#array[*]}" for ix in ${!array[*]} do printf " %s\n" "${array[$ix]}" done echo arr=(${array[*]}) echo "After unquoted expansion: ${#arr[*]}" for ix in ${!arr[*]} do printf " %s\n" "${arr[$ix]}" done echo arr=("${array[*]}") echo "After * quoted expansion: ${#arr[*]}" for ix in ${!arr[*]} do printf " %s\n" "${arr[$ix]}" done echo arr=("${array[@]}") echo "After @ quoted expansion: ${#arr[*]}" for ix in ${!arr[*]} do printf " %s\n" "${arr[$ix]}" done # Объявление функции foo() { # Аргументы функции -
s3rgeym revised this gist
Jul 11, 2019 . 1 changed file with 6 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1368,6 +1368,12 @@ man [ # Это вполне себе валидное выражение "[" 1 -eq 0 "]" || echo fail # Строка слева всегда имя переменной x=42; [[ "x" -eq "42" ]] || echo fail Fuchisaka Mitsumochi, [11.07.19 18:39] выражение слева всегда переменная case $VAR in foo) ... ;; bar) ... ;;
NewerOlder