Opensource в заметках

Find a command in your grep history

Sometimes you figure out how to do something in the terminal, and promise yourself that you’ll never forget what you’ve just learned. Then an hour goes by, and you’ve completely forgotten what you did.

Searching through your Bash history is something everyone has to do from time to time. If you know exactly what you’re searching for, you can use Ctrl+R to do a reverse search through your history, but sometimes you can’t remember the exact command you want to find.

Here’s an alias to make that task a little easier:

alias gh='history|grep'

Here’s an example of how to use it:

$ gh bash
482 cat ~/.bashrc | grep _alias
498 emacs ~/.bashrc
530 emacs ~/.bash_aliases
531 source ~/.bashrc

Sort by file size

If you started your computing life with GUI file managers like Nautilus in GNOME, the Finder in MacOS, or Explorer in Windows, then you’re probably used to sorting a list of files by their size. You can do that in a terminal as well, but it’s not exactly succinct.

Add this alias to your configuration on a GNU system:

alias lt='ls --human-readable --size -1 -S --classify'

This alias replaces lt with an ls command that displays the size of each item, and then sorts it by size, in a single column, with a notation to indicate the kind of file. Load your new alias, and then try it out:

$ source ~.bashrc
$ lt
total 344K
140K configure*
 44K aclocal.m4
 36K LICENSE
 32K config.status*
 24K Makefile
 24K Makefile.in
 12K config.log
8.0K README.md
4.0K info.slackermedia.Git-portal.json
4.0K git-portal.spec
4.0K flatpak.path.patch
4.0K Makefile.am*
4.0K dot-gitlab.ci.yml
4.0K configure.ac*
    autom4te.cache
    share
    bin
    install-sh@
    compile@
    missing@
    COPYING@

On MacOS or BSD, the ls command doesn’t have the same options, so this alias works instead:

alias lt='du -sh * | sort -h'

The results of this version are a little different:

$ du -sh * | sort -h
0       compile
0       COPYING
0       install-sh
0       missing
4.0K    configure.ac
4.0K    dot-gitlab.ci.yml
4.0K    flatpak.path.patch
4.0K    git-portal.spec
4.0K    info.slackermedia.Git-portal.json
4.0K    Makefile.am
8.0K    README.md
12K     config.log
16K     bin
24K     Makefile
24K     Makefile.in
32K     config.status
36K     LICENSE
44K     aclocal.m4
60K     share
140K    configure
476K    autom4te.cache

In fact, even on Linux, that command is useful, because using ls lists directories and symlinks as being 0 in size, which may not be the information you actually want. It’s your choice.

Thanks to Brad Alexander for this alias idea.

Чем отличается синоним от переадресации

Несмотря на то, что алиас и переадресация (редирект) приводят к одному и тому же сценарию для пользователя, технически они отличаются. Как я уже писал выше, алиасы показывают контент с основной страницы на разных адресах. Редирект же меняет ссылку и фактически отправляет человека на другой сайт.

Переадресация автоматически срабатывает при попытке ввести название популярного сайта с ошибкой. К примеру, facbook.com автоматически перенаправит на официальную страницу соцсети, то есть на facebook.com. А вот как работает переадресация Pinterest:

А еще редирект отправляет поисковой системе код 301 или 302 в зависимости от настроек сервера. Так он дает понять поисковику, стоит ли индексировать адрес, с которого сработало перенаправление (301), или его можно удалить (302).

Создание постоянных алиасов

Для создания постоянных алиасов, которые не будут удаляться после перезагрузки терминала, необходимо записать их в специальный скрытый файл — , который представляет собой обычный bash-скрипт исполняемый каждый раз при открытии терминала. 

Так как — текстовый файл, то его можно отредактировать в любом текстовом редакторе, я буду использовать редактор gedit, вы же можете использовать удобный для вас редактор будь то nano, vim или любой другой.

Для начала редактирования выполните команду ниже:

В самом конце файла добавьте нужный вам алиас и сохраните изменения. Каждый новый алиас должен начинаться с новой строки.

Добавление алиасов в файл .bashrc

Однако сразу после сохранения алиас работать не будет, так как для применения новых настроек нужно заново выполнить файл . Для этого либо просто перезагрузите консоль или выполните обновление настроек с помощью следующей команды:

Теперь ваш только что добавленный алиас будет выполняться.

Важно чтобы рядом со знаком — не было пробелов, т.е. такая запись недопустима -. Не забывайте, что вы из-за незнания какой либо команды можете переопределить ее алиасом

Так, например, если создать алиас — , то вместо попытки создания каталога с помощью команды , в консоли будет выполняться алиас, который в нашем случае, будет показывать сообщение — «wrong alias!»

Не забывайте, что вы из-за незнания какой либо команды можете переопределить ее алиасом. Так, например, если создать алиас — , то вместо попытки создания каталога с помощью команды , в консоли будет выполняться алиас, который в нашем случае, будет показывать сообщение — «wrong alias!».

Устранение неполадок при открытии файлов ALIASES

Общие проблемы с открытием файлов ALIASES

Unknown Apple II File не установлен

Дважды щелкнув по файлу ALIASES вы можете увидеть системное диалоговое окно, в котором сообщается «Не удается открыть этот тип файла». В этом случае обычно это связано с тем, что на вашем компьютере не установлено Unknown Apple II File для %%os%%. Так как ваша операционная система не знает, что делать с этим файлом, вы не сможете открыть его дважды щелкнув на него.

Совет: Если вам извстна другая программа, которая может открыть файл ALIASES, вы можете попробовать открыть данный файл, выбрав это приложение из списка возможных программ.

Установлена неправильная версия Unknown Apple II File

В некоторых случаях у вас может быть более новая (или более старая) версия файла Unknown Apple II File, не поддерживаемая установленной версией приложения. При отсутствии правильной версии ПО Unknown Apple II File (или любой из других программ, перечисленных выше), может потребоваться загрузить другую версию ПО или одного из других прикладных программных средств, перечисленных выше. Такая проблема чаще всего возникает при работе в более старой версии прикладного программного средства с файлом, созданным в более новой версии, который старая версия не может распознать.

Совет: Иногда вы можете получить общее представление о версии файла ALIASES, щелкнув правой кнопкой мыши на файл, а затем выбрав «Свойства» (Windows) или «Получить информацию» (Mac OSX).

Резюме: В любом случае, большинство проблем, возникающих во время открытия файлов ALIASES, связаны с отсутствием на вашем компьютере установленного правильного прикладного программного средства.

Даже если на вашем компьютере уже установлено Unknown Apple II File или другое программное обеспечение, связанное с ALIASES, вы все равно можете столкнуться с проблемами во время открытия файлов Unknown Apple II File. Если проблемы открытия файлов ALIASES до сих пор не устранены, возможно, причина кроется в других проблемах, не позволяющих открыть эти файлы. Такие проблемы включают (представлены в порядке от наиболее до наименее распространенных):

Бинды

Бинды происходят от название консольной команды bind, что означает присвоить какой либо клавише любую другую команду, например

bind G drop

Эта команда присваивает клавише G команду drop (выбросить оружие), т.е. если вы введете эту команду у себя в консоли, то после нажатия на клавишу G текущее оружие игрока будет выброшено.

Таким образом можно присваивать любые команды, например на выполнение какого-то действия игроком (присед, прыжок …), смену оружия, самоубийство и тд.

Бинды можно вводить в консоль игры (~), но лучше всего их вписывать в конфигурационные файлы.
Для этого нужно создать файл userconfig.cfg в дирректории «<директория с игрой>/valve/» (например C:/Games/Half-Life/valve)

Список некоторых команд

Вот небольшой список команд, которые можно забиндить

Бинды на оружие. Вместо «key» вписывайте любую свободную клавишу

bind "key" "weapon_crowbar" - лом.
bind "key" "weapon_9mmhandgun" - глок.
bind "key" "weapon_357" - револьвер.
bind "key" "weapon_9mmAR" - автомат.
bind "key" "weapon_shotgun" - дробовик.
bind "key" "weapon_crossbow" - арбалет.
bind "key" "weapon_rpg" – ракетница.
bind "key" "weapon_gauss" - гаусс.
bind "key" "weapon_egon" - пылесос .
bind "key" "weapon_hornetgun" - мухи.
bind "key" "weapon_satchel" - взрыв пакет.
bind "key" "weapon_tripmine" - растяжка.
bind "key" "weapon_granade" - ручная граната.
bind "key" "weapon_snark" - жучки.

Другие бинды

bind "key" "say Hello All" - написать фразу в чат, вместо Hello All можно ввести что-то свое

Если нужно вывести в чат сообщение на русском, то первый символ не должен относится к кириллице, это может быть любой символ (точка, запятая, цифра) или латинская буква.

bind "key" "say .Привет"

Можно также прибегнуть к небольшой хитрости, первый символ кириллической фразы заменить аналогом из латиницы.

bind "key" "say Bсем привет!" - первая буква - b заглавная
bind "key" "drop" - сбросить балон с оружием. 
bind "key" "stopsound" - отключить звук.
bind "key" "model barney" - установить модель
bind "key" "name SuperPlayer" - установить ник
bind "k" "kill" - самоубийство

Таким образом можно забиндить любую команду которая присутствует в Half-Life

Примечание! Чтобы использовать бинды с русскими фразами конфигурационный файл необходимо сохранять в кодировке UTF-8, это делается в блокноте при сохранении.

View only mounted drives

The mount command used to be so simple. With just one command, you could get a list of all the mounted filesystems on your computer, and it was frequently used for an overview of what drives were attached to a workstation. It used to be impressive to see more than three or four entries because most computers don’t have many more USB ports than that, so the results were manageable.

Computers are a little more complicated now, and between LVM, physical drives, network storage, and virtual filesystems, the results of mount can be difficult to parse:

sysfs on /sys type sysfs (rw,nosuid,nodev,noexec,relatime,seclabel)
proc on /proc type proc (rw,nosuid,nodev,noexec,relatime)
devtmpfs on /dev type devtmpfs (rw,nosuid,seclabel,size=8131024k,nr_inodes=2032756,mode=755)
securityfs on /sys/kernel/security type securityfs (rw,nosuid,nodev,noexec,relatime)

/dev/nvme0n1p2 on /boot type ext4 (rw,relatime,seclabel)
/dev/nvme0n1p1 on /boot/efi type vfat (rw,relatime,fmask=0077,dmask=0077,codepage=437,iocharset=utf-8,shortname=winnt,errors=remount-ro)

gvfsd-fuse on /run/user/100977/gvfs type fuse.gvfsd-fuse (rw,nosuid,nodev,relatime,user_id=100977,group_id=100977)
/dev/sda1 on /run/media/seth/pocket type ext4 (rw,nosuid,nodev,relatime,seclabel,uhelper=udisks2)
/dev/sdc1 on /run/media/seth/trip type ext4 (rw,nosuid,nodev,relatime,seclabel,uhelper=udisks2)
binfmt_misc on /proc/sys/fs/binfmt_misc type binfmt_misc (rw,relatime)

To solve that problem, try an alias like this:

alias mnt="mount | awk -F' ' '{ printf \"%s\t%s\n\",\$1,\$3; }' | column -t | egrep ^/dev/ | sort"

This alias uses awk to parse the output of mount by column, reducing the output to what you probably looking for (what hard drives, and not file systems, are mounted):

$ mnt
/dev/mapper/fedora-root  /
/dev/nvme0n1p1           /boot/efi
/dev/nvme0n1p2           /boot
/dev/sda1                /run/media/seth/pocket
/dev/sdc1                /run/media/seth/trip

On MacOS, the mount command doesn’t provide terribly verbose output, so an alias may be overkill. However, if you prefer a succinct report, try this:

alias mnt='mount | grep -E ^/dev | column -t'

The results:

$ mnt
/dev/disk1s1  on  /                (apfs,  local,  journaled)
/dev/disk1s4  on  /private/var/vm  (apfs,  local,  noexec,     journaled,  noatime,  nobrowse)

Add a copy progress bar

Everybody pokes fun at progress bars because they’re infamously inaccurate. And yet, deep down, we all seem to want them. The UNIX cp command has no progress bar, but it does have a -v option for verbosity, meaning that it echoes the name of each file being copied to your terminal. That’s a pretty good hack, but it doesn’t work so well when you’re copying one big file and want some indication of how much of the file has yet to be transferred.

The pv command provides a progress bar during copy, but it’s not common as a default application. On the other hand, the rsync command is included in the default installation of nearly every POSIX system available, and it’s widely recognized as one of the smartest ways to copy files both remotely and locally.

Better yet, it has a built-in progress bar.

alias cpv='rsync -ah --info=progress2'

Using this alias is the same as using the cp command:

$ cpv bigfile.flac /run/media/seth/audio/
          3.83M 6%  213.15MB/s    0:00:00 (xfr#4, to-chk=0/4)

An interesting side effect of using this command is that rsync copies both files and directories without the -r flag that cp would otherwise require.

Alias command with examples

Let us start learning Linux alias command with examples

Example1: Create an alias for getting memory states on the machine

Alias RAM=’free -m’

Output:

$ alias RAM='free -m'
linuxnix@ssh01 ~]$ RAM             
total       used       free     shared    buffers     cached Mem:         15936        521      15414          0        137        157 -/+ buffers/cache:        225      15710 Swap:         8039          0       8039 $

Example2: Defining multiple aliases within a single line

alias p="pwd"; l="ls -al"

Example3: Alias support command chaining as well such as semi-colon, pipe, && and || with these operations we can run multiple commands

A couple of examples on this:

Example: Write an alias which shows RAM, uptime, OS details

Example:

$ alias sd='free -m;w;uname -a'
$ sd             
total       used       free     shared    buffers     cached Mem:         15936        521      15414          0        137        157 -/+ buffers/cache:        225      15710 Swap:         8039          0       8039  01:06:37 up 330 days,  8:39,  1 user,  load average: 0.00, 0.00, 0.00 USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT linuxnix  pts/0    145.230.134.71   00:41    0.00s  0.26s  0.00s w Linux ssh01.plan 2.6.32-358.el6.x86_64 #1 SMP Fri Feb 22 00:31:26 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux $

What about command chaining with an alias?

Below are some alias commands which use command chaining

Semicolon operator

alias a=’cmd1;cmd2;cmd3’

Pipe operator

alias b=’cmd1 | cmd2 | cmd3’

Logical AND operation

alias c=’cmd1 && cmd2 && cmd3’

Logical OR operation

alias d=’cmd1 || cmd2’

In fact, you can use many of the command chaining options with an alias.

Пример ALIAS таблицы

Когда вы создаете псевдоним в таблице, это либо потому, что вы планируете перечислить одно и то же имя таблицы более одного раза в операторе FROM (т.е.: при присоединении), или вы хотите сократить имя таблицы, чтобы сделать оператор SQL короче и удобочитаемым.

Рассмотрим пример псевдонима имени таблицы в MySQL. Например:

MySQL

SELECT p.product_id, p.product_name, suppliers.supplier_name
FROM products p
INNER JOIN suppliers
ON p.supplier_id = suppliers.supplier_id
ORDER BY p.product_name ASC, suppliers.supplier_name DESC;

1
2
3
4
5

SELECTp.product_id,p.product_name,suppliers.supplier_name

FROMproductsp

INNER JOINsuppliers

ONp.supplier_id=suppliers.supplier_id

ORDER BYp.product_nameASC,suppliers.supplier_nameDESC;

В этом примере мы создали псевдоним p для таблицы products. Теперь в этом SQL-предложении мы можем ссылаться на таблицу products как p.

При создании псевдонимов таблиц нет необходимости создавать псевдонимы для всех таблиц, перечисленных в операторе FROM. Вы можете создавать псевдонимы на любой или всех таблицах.

Например, мы могли бы изменить наш пример выше и создать псевдоним для таблицы suppliers.

MySQL

SELECT p.product_id, p.product_name, s.supplier_name
FROM products p
INNER JOIN suppliers s
ON p.supplier_id = s.supplier_id
ORDER BY p.product_name ASC, s.supplier_name DESC;

1
2
3
4
5

SELECTp.product_id,p.product_name,s.supplier_name

FROMproductsp

INNER JOINsupplierss

ONp.supplier_id=s.supplier_id

ORDER BYp.product_nameASC,s.supplier_nameDESC;

Теперь у нас есть псевдоним для таблицы suppliers, именуемый s, а также псевдоним для таблицы products p.

Как создать алиас домена на VDS в TimeWeb

Чтобы добавить синоним домена, надо отредактировать конфигурационные файлы Nginx и Apache.

Сначала настраиваем Nginx. Поочередно открываем файлы:

nano /etc/nginx/site_available/название-сайта.conf

Здесь и далее указаны стандартные пути к конфигурационным файлам. Они могут отличаться в зависимости от используемого окружения. Например, для  адрес будет другим.

Ищем там строчку server_name и прописываем названия синонимов через пробел от канонического домена. Например:

server_name timeweb.com taimweb.com timeweb.ru

Потом открываем конфигурационный Apache:

nano /etc/nginx/site_available/название-сайта.conf

Находим внутри строку ServerAlias и после основного домена через пробел прописываем дополнительные. Например:

ServerAlias www.timeweb.com timeweb.ru

Затем внесенные изменения и серверы.

Пример настройки привязки доменов для виртуального хостинга.

Склейка сайтов

Если у вас уже есть несколько сайтов, то их можно «склеить» в один для корректной индексации со стороны поисковых систем. В зависимости от выбранного поисковика процесс склейки может отличаться.

  • Инструкция для Яндекса.
  • Инструкция для (надо сделать редирект 301).

Это все, чем я хочу с вами поделиться. Теперь вам известно, что такое алиас домена и как его создать. Известно, как с ним работать и чем он отличается от редиректа. Необходимый базис получен.

Делаем простые команды ещё проще

Возьмём, например, часто многими используемую команду ‘ls -l’, отображающую список файлов в каталоге в т. н. «длинном» формате. Можно упростить ввод этой чатсо используемой команды. Например, так:

alias ll="ls -l"

Теперь вместо ‘ls -l’ вы можете вводить ‘ll’ и получать список файлов в «длинном» формате.

Ещё пример. Иногда впопыхах или после пары банок пива усталые пользователи начинают вводить ‘sl’ вместо ‘ls’ и очень нервничают по этому поводу. Исправим эту неприятность:

alias sl="ls"

Вот ещё более простой пример, используя который, можно ускорить ввод команды exit:

alias x="exit"

Следующие три примера делают популярные команды более интерактивными по умолчанию:

alias cp="cp -iv"
alias mv="mv -iv"
alias rm="rm -iv"

Упрощаем управление пакетами

Почти во всех современных дистрибутивах имеется система управления пакетами, а также набор программного обеспечения для работы с ней. Ниже, на примере менеджера управления пакетами APT, используемом в Debian и его потомках, автор демонстрирует способ упрощения работы с ним.

Для того, чтобы установить какой-то пакет в Debian/Ubuntu, обычно используется команда:

sudo apt-get install имя_пакета

Эта длинная команда отбирает много времени, сил и энергии. Давайте упростим её при помощи alias;

alias Install="sudo apt-get install"

Теперь устанавливать пакеты стало проще:

Install имя_пакета

Таким же образом можно упростить остальные часто используемые моменты при управлении пакетами:

alias Update=”sudo apt-get update”
alias Upgrade=”sudo apt-get upgrade”
alias Search=”apt-cache search”
alias Autoremove=”sudo apt-get autoremove”
alias Autoclean=”sudo apt-get autoclean”
alias Purge=”sudo apt-get remove –purge”

Protect yourself from file removal accidents

You shouldn’t use the rm command. The rm manual even says so:

If you want to remove a file, you should move the file to your Trash, just as you do when using a desktop.

POSIX makes this easy, because the Trash is an accessible, actual location in your filesystem. That location may change, depending on your platform: On a FreeDesktop, the Trash is located at ~/.local/share/Trash, while on MacOS it’s ~/.Trash, but either way, it’s just a directory into which you place files that you want out of sight until you’re ready to erase them forever.

This simple alias provides a way to toss files into the Trash bin from your terminal:

alias tcn='mv --force -t ~/.local/share/Trash '

This alias uses a little-known mv flag that enables you to provide the file you want to move as the final argument, ignoring the usual requirement for that file to be listed first. Now you can use your new command to move files and folders to your system Trash:

$ ls 
foo  bar
$ tcn foo
$ ls
bar 

Now the file is «gone,» but only until you realize in a cold sweat that you still need it. At that point, you can rescue the file from your system Trash; be sure to tip the Bash and mv developers on the way out.

Note: If you need a more robust Trash command with better FreeDesktop compliance, see Trashy.

Alias Examples

Now that you know how to create your own aliases, let’s talk about some popular ones that may be useful to you. These can be found throughout the web, and some may also be included in your distribution’s default bash configuration as well.

Navigation and Listing

Many of the most simple Linux commands are more helpful when you apply some formatting and options.

We discussed one example above, but there are many others you may find.

Make display in columns and with a file type indicator (end directories with ”/“, etc) by default:

We can also anticipate some typos to make it call the correct command:

Let’s also make an alias to pipe our output to for viewing large directory listings with the long format:

How about we stray from and try some helpful commands for .

This one will change to your parent directory, even when you forget the space:

You can also cut out the part entirely by making an alias for :

We can find files in our current directory easily by setting this alias:

System Aliases

How about some of our monitoring and system stats commands? I call these with the same options every time, so I might as well make some aliases.

This one will list our disk usage in human-readable units including filesystem type, and print a total at the bottom:

We might as well add an alias for our preferred output as well:

Let’s keep going in the same direction by making our output more human friendly:

We can do a lot with our listing process table. Let’s start out by setting a default output:

How about we make our process table searchable. We can create an alias that searches our process for an argument we’ll pass:

Now, when we call it with the process name we’re looking for as an argument, we’ll get a nice, compact output:

Miscellaneous Aliases

One common option to the command that we use often is the flag to make any necessary parent directories. We can make this the default:

We might want to add a flag on top of that so we are told of every directory creation, which can help us recognize quickly if we had a typo which caused an accidental directory branch:

When downloading files from the internet with , in almost all circumstances, you’ll want to pass the flag in order to continue the download in case of problems. We can set that with this:

We can search our history easily like with a grep of the command’s output. This is sometimes more useful than using CTRL-R to reverse search because it gives you the command number to do more complex recalls afterwards:

I have a few system tools that I prefer to upgrade from the standard version to more complex tools. These will only work if you’ve downloaded the required utilities, but they can be very helpful. Keep in mind that these may affect your other aliases.

This one replaces the conventional command with an enhanced version that is much easier on the eyes and can be sorted, searched, and scrolled without complications:

In a similar way, the command can be downloaded which presents file and directory sizes in an interactive ncurses display that you can browse and use to perform simple file actions:

There’s an upgraded utility for as well that’s called . It provides colorized output and text-based usage bars. We can default to using this utility if we have it:

Have you ever needed your public IP address from the command line when you’re behind a router using NAT? Something like this could be useful:

For my own purposes, I like to optimize the images I upload for articles to be 690px or less, so I use the ImageMagick package ( if not already available) which contains a command called that does just this. I have this command in my file:

This will resize all of the PNG images in the current directory, only if they are wider than 690px.

If I then have to upload them to a server, I can use to connect and automatically change to a specific directory:

<pre>
alias upload=»sftp <span class=»highlight”>username</span>@<span class=“highlight”>server.com</span>:<span class=“highlight”>/path/to/upload/directory</span>
</pre>

Примеры Aliases для столбцов

Следующая инструкция SQL создает два псевдонима, один для столбца идентификатора и один для столбца CustomerName:

Пример

SELECT CustomerID as ID, CustomerName AS Customer
FROM Customers;

Следующая инструкция SQL создает два псевдонима: один для столбца CustomerName и один для столбца ContactName. Примечание: Он требует двойных кавычек или квадратных скобок, если псевдоним содержит пробелы:

Пример

SELECT CustomerName AS Customer, ContactName AS
FROM Customers;

Следующая инструкция SQL создает псевдоним с именем «Address», объединяющий четыре столбца (адрес, PostalCode, город и страна):

Пример

SELECT CustomerName, Address + ‘, ‘ + PostalCode + ‘ ‘ + City + ‘, ‘ + Country
AS Address
FROM Customers;

Примечание: Чтобы получить инструкцию SQL выше для работы в MySQL, используйте следующее:

SELECT CustomerName, CONCAT(Address,’, ‘,PostalCode,’, ‘,City,’, ‘,Country) AS Address
FROM Customers;

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *