How to create alias in linux

How to Create and Use Alias Command in Linux

Linux users often need to use one command over and over again. Typing or copying the same command again and again reduces your productivity and distracts you from what you are actually doing.

You can save yourself some time by creating aliases for your most used commands. Aliases are like custom shortcuts used to represent a command (or set of commands) executed with or without custom options. Chances are you are already using aliases on your Linux system.

List Currently Defined Aliases in Linux

You can see a list of defined aliases on your profile by simply executing alias command.

Here you can see the default aliases defined for your user in Ubuntu 18.04.

List Aliases in Linux

As you can see, executing.

Is equivalent to running:

You can create an alias with a single character that will be equivalent to a command of your choice.

How to Create Aliases in Linux

Creating aliases is relatively easy and quick process. You can create two types of aliasestemporary ones and permanent. We will review both types.

Creating Temporary Aliases

What you need to do is type the word alias then use the name you wish to use to execute a command followed by «=» sign and quote the command you wish to alias.

The syntax is as follows:

Here is an actual example:

You can then use «wr» shortcut to go to the webroot directory. The problem with that alias is that it will only be available for your current terminal session.

If you open new terminal session, the alias will no longer be available. If you wish to save your aliases across sessions you will need a permanent alias.

Creating Permanent Aliases

To keep aliases between sessions, you can save them in your user’s shell configuration profile file. This can be:

The syntax you should use is practically the same as creating a temporary alias. The only difference comes from the fact that you will be saving it in a file this time. So for example, in bash, you can open .bashrc file with your favorite editor like this:

Find a place in the file, where you want to keep the aliases. For example, you can add them in the end of the file. For organizations purposes you can leave a comment before your aliases something like this:

Save the file. The file will be automatically loaded in your next session. If you want to use the newly defined alias in the current session, issue the following command:

To remove an alias added via the command line can be unaliased using unalias command.

Conclusion

This was a short example on how to create your own alias and execute frequently used commands without having to type each command again and again. Now you can think about the commands you use the most and create shortcuts for them in your shell.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

Читайте также:  Nextcloud windows client cycling login grant access

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

How to create an alias in Linux

As system administrators and command-line enthusiasts, we inevitably find ourselves using the same commands ad nauseam. If we are any good at our jobs, we should always strive to make our processes more efficient. The goal is to ultimately «do more with less.»

More Linux resources

One of the first articles I wrote for Enable Sysadmin, which you can find here, was about the AutoHotkey tool for Windows. This is a fantastic utility that allows you to set up a user-friendly script that lightens your workload. As I have yet to find a suitable substitute for this tool in Linux, I looked into setting up aliases for the commands that I use regularly. Since I am no longer working in the support sector, most of these are just quality of life changes. Once you understand how to configure an alias, this process can be applied to almost any situation.

Aliases

First things first: What is an alias, and why do I care? Well, an alias is a custom command created by the user to execute another, usually more complicated command or group of commands. The utility of aliases can be seen in ‘Decluttering process management’, where I mention an alias I created for the following command:

Instead of typing this full command, I created an alias that allows me to use pscgroup to execute the original, much longer command. Now that you can see the utility on offer, let’s take a look at where and how to configure our aliases.

[Want to try out Red Hat Enterprise Linux? Download it now for free.]

Creating aliases

There are a few things to note when creating aliases. For the purpose of this article, aliases are built on a user-by-user basis. If I create an alias as user tcarrigan and then change to the root user, the created alias will not work. Here you can see I aliased ls to use a program called EXA that displays additional information and adds color-coding. The same command, in the same directory as the root user, displays the standard output for ls :

There are locations where you can create aliases to span all users. For more information on this topic, check out the bash shell documentation.

For now, we will create our alias under user testuser . So, in my home directory, I enter my alias into .bashrc . Keep in mind that this file is hidden by default. It can be seen by adding the -a flag to your ls command:

You can see that this user starts with no aliases. We will correct this situation soon. For now, we will look at the command syntax. The correct syntax is as follows:

We will now alias the ls command to ls -lra so that you get a much better look at all of your files, both hidden and non-hidden:

Now, reload the .bashrc file using the following command:

When you use the standard ls command now, you can see that the alias is now active, giving you the output for ls -lra :

Wrapping up

While this alias is a simple quality of life change, you can apply this same concept to long and complicated commands that you might have to use routinely during your daily work. Let us know what some of your favorite use cases are. We at Enable Sysadmin look forward to hearing from you.

Источник

Полезные alias Linux

Alias Linux — это, по сути, ярлыки команд Linux. Команда alias позволяет пользователю запускать любую команду или даже группу команд, в том числе с опциями, параметрами и файлами, вводом одного слова или даже символа. Это очень удобно во многих ситуациях, например чтобы не вводить полностью команду при обновлении или же очень быстро перемещаться по каталогам.

В этой инструкции будет рассмотрена команда alias linux, а также полезные алиасы, которые без сомнения must have в каждой системе.

Команда alias

Чтобы посмотреть какие псевдонимы linux команд уже заданны в вашей системе просто выполните:

Читайте также:  Teamcity agent mac os

В выводе вы увидите что-то подобное:

Команда покажет все alias команд linux определенные для текущего пользователя. Вывод очень сильно зависит от вашего дистрибутива. Общий синтаксис команды выглядит следующим образом:

$ alias имя = «значение»

$ alias имя = «команда аргумент1 аргумент2»

$ alias имя = «/путь/к/исполняемому/файлу»

Вы можете создавать новые псевдонимы, просто выполняя эту команду в терминале. Но созданные таким образом алиасы linux будут работать только в этом терминале и только до его закрытия.

Давайте для примера создадим alias linux для такой часто используемой команды, как clear (очистить вывод терминала):

Теперь, чтобы очистить терминал достаточно выполнить:

Удалить созданный alias можно с помощью команды unalias:

Но как я уже сказал, такие alias команд linux сохраняются только до закрытия терминала. Поэтому их необходимо создавать в начале каждой терминальной сессии. Для этого можно записать все нужные команды в

/.bashrc. При запуске терминала, каждый раз выполняется этот скрипт, чтобы установить переменные окружения и подготовить оболочку. Таким образом добавив нужные строки в конец файла мы получим работающие alias linux в каждом терминале.

Продолжим создание alias для команды clear:

Добавьте эту строку в конец файла:

Затем сохраните и закройте редактор (:wq). Чтобы проверить работоспособность запустите новый терминал. Если вы хотите чтобы ваши алиасы linux были доступны для всех пользователей, необходимо использовать файл /etc/bashrc.

Поскольку .bashrc, это обычный bash скрипт, перед нами открываются большие возможности. Например мы можем добавить alias команд с использованием sudo, если текущий пользователь не root:

if [ $UID -ne 0 ]; then
alias reboot=’sudo reboot’
alias update=’sudo apt-get upgrade’
fi

Ещё мы можем менять команды алиасов в зависимости от дистрибутива:

_myos=»$(uname)»
case $_myos in
Linux) alias foo=’/path/to/linux/bin/foo’;;
FreeBSD|OpenBSD) alias foo=’/path/to/bsd/bin/foo’ ;;
SunOS) alias foo=’/path/to/sunos/bin/foo’ ;;
*) ;;
esac

Чтобы удалить alias достаточно просто удалить запись о нем, из того файла в который вы её добавили. Мы рассмотрели основы добавления alias linux, теперь давайте перейдем к списку полезных алиасов linux.

Полезные alias Linux

Вы можете добавить в своей системе любые или даже все эти алиасы linux чтобы повысить продуктивность своей работы в терминале.

1. Вывод ls

alias ls=’ls —color=auto’

Показывать скрытые файлы и представлять вывод в виде списка:

Показать только скрытые файлы:

alias l.=’ls -d .* —color=auto’

2. Перемещение по каталогам

Быстрое перемещение от текущей директории:

3. Вывод grep

Делаем вывод цветным:

alias grep=’grep —color=auto’
alias egrep=’egrep —color=auto’
alias fgrep=’fgrep —color=auto’

4. Калькулятор

Запускать калькулятор с поддержкой стандартной библиотеки mathlib:

5. Создание каталогов

Создавать дерево каталогов, если оно не существует:

alias mkdir=’mkdir -pv’

6. Вывод diff

Делаем вывод diff цветным:

7. Вывод mount

Сделаем вывод mount читаемым:

alias mount=’mount | column -t’

8. История

Сократим команды для экономии времени:

alias h=’history’
alias j=’jobs -l’

9. Информация и дата

alias path=’echo -e $
alias now=’date +»%T»‘
alias nowtime=now
alias nowdate=’date +»%d-%m-%Y»‘

10. Редактор Vim

alias команд linux для использования редактора vim по умолчанию:

alias vi=vim
alias svi=’sudo vi’
alias vis=’vim «+set si»‘
alias edit=’vim’

11. Ping

Посылать только пять запросов:

alias ping=’ping -c 5′

Интервал между запросами одна секунда:

alias fastping=’ping -c 100 -s.2′

12. Открытые порты

alias ports=’netstat -tulanp’

13. Wakeup

Будим серверы в режиме сна по mac адресу с помощью утилиты wakeonlan:

alias wakeupnas01=’/usr/bin/wakeonlan 00:11:32:11:15:FC’
alias wakeupnas02=’/usr/bin/wakeonlan 00:11:32:11:15:FD’
alias wakeupnas03=’/usr/bin/wakeonlan 00:11:32:11:15:FE’

14. Управление iptables

alias iptlist=’sudo /sbin/iptables -L -n -v —line-numbers’
alias iptlistin=’sudo /sbin/iptables -L INPUT -n -v —line-numbers’
alias iptlistout=’sudo /sbin/iptables -L OUTPUT -n -v —line-numbers’
alias iptlistfw=’sudo /sbin/iptables -L FORWARD -n -v —line-numbers’
alias firewall=iptlist

15. Утилита curl

Получить заголовки сервера:

alias header=’curl -I’

Проверять поддержку сжатия на сервере:

alias headerc=’curl -I —compress’

16. Работа с файлами

Не удалять корень и предупреждать об удалении файлов:

alias rm=’rm -I —preserve-root’

alias mv=’mv -i’
alias cp=’cp -i’
alias ln=’ln -i’

Защита от изменения прав для /:

alias chown=’chown —preserve-root’
alias chmod=’chmod —preserve-root’
alias chgrp=’chgrp —preserve-root’

17. Обновление Debian

alias apt=»sudo apt»
alias updatey=»sudo apt —yes»

Обновление одной командой:

alias update=’sudo apt update && sudo apt upgrade’

18. Обновление RedHat

В семействе дистрибутивов Red Hat используется пакетный менеджер yum:

alias update=’yum update’
alias updatey=’yum -y update’

19. Стать суперпользователем

alias root=’sudo -i’
alias su=’sudo -i’

20. Выключение

Выполнять команды выключения через sudo:

Читайте также:  Виджеты для windows 10 выключение компьютера

alias reboot=’sudo /sbin/reboot’
alias poweroff=’sudo /sbin/poweroff’
alias halt=’sudo /sbin/halt’
alias shutdown=’sudo /sbin/shutdown’

21. Управление серверами

alias nginxreload=’sudo /usr/bin/nginx -s reload’
alias nginxtest=’sudo /usr/bin/nginx -t’
alias lightyload=’sudo systemctl reload lighttpd’
alias lightytest=’sudo /usr/sbin/lighttpd -f /etc/lighttpd/lighttpd.conf -t’
alias httpdreload=’sudo /usr/sbin/apachectl -k graceful’
alias httpdtest=’sudo /usr/sbin/apachectl -t && /usr/sbin/apachectl -t -D DUMP_VHOSTS’

22. Мультимедиа

Открыть видео в текущей директории:

alias playavi=’mplayer *.avi’
alias vlc=’vlc *.avi’

Добавить в плейлист музыку из текущей директории:

alias playwave=’for i in *.wav; do mplayer «$i»; done’
alias playogg=’for i in *.ogg; do mplayer «$i»; done’
alias playmp3=’for i in *.mp3; do mplayer «$i»; done’

Открыть музыку из устройства nas:

alias nplaywave=’for i in /nas/multimedia/wave/*.wav; do mplayer «$i»; done’
alias nplayogg=’for i in /nas/multimedia/ogg/*.ogg; do mplayer «$i»; done’
alias nplaymp3=’for i in /nas/multimedia/mp3/*.mp3; do mplayer «$i»; done’

22. Системное администрирование

Работать с интерфейсом eth1:

alias dnstop=’dnstop -l 5 eth1′
alias vnstat=’vnstat -i eth1′
alias iftop=’iftop -i eth1′
alias tcpdump=’tcpdump -i eth1′
alias ethtool=’ethtool eth1′

Работать с интерфейсом wlan0 по умолчанию:

alias iwconfig=’iwconfig wlan0′

23. Информация о системе

alias meminfo=’free -m -l -t’

Показать процессы потребляющие больше всего памяти:

alias psmem=’ps auxf | sort -nr -k 4′
alias psmem10=’ps auxf | sort -nr -k 4 | head -10′

Показать процессы использующие процессор:

alias pscpu=’ps auxf | sort -nr -k 3′
alias pscpu10=’ps auxf | sort -nr -k 3 | head -10′

Информация о процессоре:

Посмотреть память видеокарты:

alias gpumeminfo=’grep -i —color memory /var/log/Xorg.0.log’

25. Утилита wget

Продолжать незавершенную загрузку по умолчанию:

alias wget=’wget -c’

26. Браузеры

alias ff=’/usr/bin/firefox’
alias chrome=’/usr/bin/google-chrome’
alias opera=’/usr/bin/opera’
alias chromium=’/usr/bin/chromium’

Браузер по умолчанию:

27. Правильные единицы измерения

Правильное отображение данных для free, df и du:

alias df=’df -H’
alias du=’du -ch’
alias free=’free -h’

Выводы

Если вы знаете другие полезные alias команд linux, то поделитесь ими с нами в комментариях!

Оцените статью:

Об авторе

Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.

10 комментариев

Кхе, кхе. Что будет — ежели сотворить текстовый файл с набором alias, который будучи вставленным в

/.bashrc после первой установки системы, выполнял бы обновление, удаление гостевого сеанса, открывал бы скрытые пункты автозагрузки? Список можно продолжить. Черновой работы подобного рода море, особенно в классической Ubuntu.
P.S. Не судите строго. 😉

Интересно, но это уже не alias, а просто скрипт.

это и есть алиася. Или сделать /etc/profile.d/aliases.sh — рекомеднуют туда. Это для всех пользователей будет действовать.
Еще бы статью про функции, я их тоже в /etc/profile.d/файл помещаю. Но надо обязательно все проверить перед перезагрузкой.
И к функциям сделать bash-completion

Хмм. Можно попробовать
alias sizes=»du —summarize —human-readable *»
df -h и free -h по умолчанию
Обновление, наверное, лучше всё же скриптами. Тот же «

root/update » лично у меня запускает что-то вида emerge -DuNv$1 $2 —keep-going @world && emerge -vD$1 $2 —depclean && emerge @preserved-rebuild && revdep-rebuild && beep -f 2000 -l 50 || beep -f 100 -l 150″ плюс записывает время начала выполнения, time разных процессов обновления, запускает пакетный менеджер с нужными nice и ionice, и так далее. В перспективе можно прикрутить к этому cgroups, чтоб уж точно не поджимал по быстродействию, и цветное перенаправление во временные файлы для дальнейшего курения в случае ошибок. А запускаться всё равно будет так же. И не надо писать лютый однострочник с сомнительной поддержкой переменных и прочего.

Введенные на не_той раскладе команды, алиас запуска не умеющего в rc-файлы эмулятора терминала, sublime-text=»/opt/. «, и так далее. Простор огромен.

//а, и ещё манпейджи говорят про интересные применения в плане чтения истории команд плюс команду «type», показывающую текущие алиасы для команды, и «command», пропускающую алиасы при выполнении.

Ну и удобные алиасы для каждого всё равно будут своими.

Что бы не корёжить файл .bashrc, можно создать рядом файл .bash_aliases и добавлять алиасы в него.

Хорошая статья. Я делаю дополнительный файл алиасов — host-specific. Модифицирую .bashrc добавив пару строчек.

[[ -f $HOME/.bashrc.$HOSTNAME ]] && . «$HOME/.bashrc.$HOSTNAME»

Хорошо бы еще написать статью про внедрение функций для расширения функционала. (PS прошу прощения если таковая уже иммется. )

Допустим, я сделал алиас apt=’aptitude’.
Как мне вызвать прежний apt (unalias не предлагать)?

Источник

Оцените статью