- How to create an alias in Linux
- More Linux resources
- Aliases
- Creating aliases
- Wrapping up
- Создание синонимов команд в Linux. Команда alias
- Создание синонимов (команда alias)
- Синтаксис команды alias
- Примеры создания синонимов
- Сохранение синонимов
- Просмотр списка синонимов
- Удаление синонимов
- Несколько примеров синонимов
- Создание синонимов, используя Bash-функции (синонимы с аргументами)
- Синтаксис функций в Bash
- Примеры создания функций
- Заключение
- Linux alias command: How to create and use Linux aliases
- Using Linux aliases
- Alias examples
- How to define a Linux alias
- Unix/Linux alias examples and syntax
- Have a favorite Linux alias?
- Using alias Command in Linux to Improve Your Efficiency
- Linux alias command
- How to create alias in Linux
- Make alias permanent
- Creating global aliases for all users
- How to see all the alias set on your Linux system for you
- How to remove alias
- My favorite alias in Linux I cannot live without
- 1. Making ‘rm’ safer
- 2. Making ssh to other systems easier and faster
- 3. Show time or date for day to day things
- 4. Easily manage your iptables information
- 5. Update Debian based servers in one single command
- 6. Add an alias to run alias with sudo
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.
Источник
Создание синонимов команд в Linux. Команда alias
В Linux можно создавать синонимы для других команд. Рассмотрим, как это сделать.
Синонимы для команд (или псевдонимы, или алиасы) — это команда, состоящая из одного слова, но выполняющая другую заданную команду. Это удобно, например, когда нужно часто выполнять длинную команду или команду с различными ключами. Вместо ввода длинной команды достаточно выполнить одну команду-синоним.
Создание синонимов (команда alias)
В командной оболочке Bash для создания синонимов используется команда alias .
Синтаксис команды alias
Чтобы создать синоним нужно указать команду-синоним и в кавычках указать команду , которая должна выполняться:
синоним — короткая команда (алиас), которая будет использоваться для запуска команды .
команда — команда, которая будет запускаться при вызове синонима . Записывается в двойных или одинарных кавычках.
Примеры создания синонимов
Вывод списка файлов:
То есть, вместо выполнения ls -la теперь достаточно выполнить команду ll :
Создадим команду для быстрого перехода в заданную директорию:
Подключение по ssh к определенному серверу:
Сохранение синонимов
Когда вы создаете синоним с помощью команды alias, то он функционирует только в текущей сессии, пока открыто окно терминала. Чтобы сохранить синонимы на постоянной основе, нужно прописать выполнение команд alias в файл .bashrc .
Запустите терминал и откройте файл .bashrc для редактирования, выполнив команду:
Перейдите в конец файла и введите команды для создания синонимов, по одному на каждой строчке, например:
Сохраните изменения и закройте файл. Для этого нажмите Ctrl+X , откроется запрос на сохранение изменений в файле — нажмите y и затем Enter .
Чтобы изменения вступили в силу, можно выйти и снова войти в систему или выполните команду:
Просмотр списка синонимов
Чтобы просмотреть список всех активных в данный момент синонимов используется команда:
Во многих дистрибутивах несколько синонимов уже может быть создано в системе. Например у меня результат следующий:
Удаление синонимов
Чтобы удалить синоним используется команда unalias . Удаление происходит только в текущей сессии терминала.
Удаление синонима по заданному имени:
Удаление всех синонимов:
Несколько примеров синонимов
Очистка окна терминала:
Вывод подробного списка файлов:
Вывод списка скрытых файлов:
Поиск по истории команд (запускается, например, так hs ssh ):
Показать список открытых портов:
Выполнять ping только 5 раз, а не бесконечно:
Узнать свой внешний IP-адрес:
Создание синонимов, используя Bash-функции (синонимы с аргументами)
Командная оболочка Bash позволяет создавать функции, которые могут выполнять одну или несколько команд. Они относятся к программированию в Bash, но их иногда можно использовать и для создания синонимов. Такие функции могут принимать аргументы в командой строке, в отличии от синонимов, создаваемых командой alias.
Синтаксис функций в Bash
Данный код создает функцию , которая выполняет команды . Команда может быть одна или несколько. Чтобы выполнить функцию достаточно ввести в командной строке ее название. Через пробел можно передавать аргументы.
Чтобы внутри функции обратиться к аргументам, используются сокращения $1 , $2 и т.д. $1 соответсвует первому аргументу, $2 второму и т.д. $0 соответсвует имени функции.
Примеры создания функций
Функции можно создавать прямо в текущей сессии терминала, но лучше прописать их в файле .bashrc .
Создадим функцию которая принимает имя директории, создает данную директорию и переходит в нее:
Теперь, вместо того, чтобы выполнять mkdir для создания директории, а затем cd , чтобы перейти в нее, достаточно выполнить:
У вас может возникнуть вопрос, что означают символы — и && внутри нашей функции?
- — — используется, чтобы указать, конец опций команды. То есть все, что будет записываться после — это уже аргументы и они не будут интерпретироваться, как опции для данной команды. В нашем примере мы можем попробовать создать директорию имя которой начинается с символа — , и если бы мы не использовали — , то команда mkdir подумала бы, что мы пытаемся передать ей не имя директории а опцию.
- && — логическое И — сначала выполняется команда, стоящая слева от && и только если она выполнена успешно, запускается команда, стоящая справа от && .
Заключение
Синонимы команд в Linux очень удобный инструмент, упрощающий работу с системой. В данной статье мы рассмотрели создание синонимов командой alias , а также использование функций Bash для создания синонимов.
Не смотря на удобство использования синонимов, сильно увлекаться ими не стоит. Не нужно создавать тонну алиасов на все случаи жизни. Это может привести к путанице и банальному незнанию полных команд, когда пересаживаешься за другой компьютер.
Также нужно быть крайне аккуратным при создании синонимов, которые имеют такое же имя, как и сама команда, которую они выполняют. Переписывая таким образом поведение команды, выполнение синонима, вместо команды, иногда может приводить к неочевидным результатам.
Источник
Linux alias command: How to create and use Linux aliases
Unix/Linux aliases FAQ: Can you share some examples of the Linux alias command?
Using Linux aliases
Aliases in Unix and Linux operating systems are cool. They let you define your own commands, or command shortcuts, so you can customize the command line, and make it work the way you want it to work. In this tutorial I’ll share several Linux aliases that I use on a daily basis.
Alias examples
I’ve found it very helpful to create aliases to make my command line life easier. For instance, a lot of people don’t like the name of the grep command, and wish they could change it to search . With the alias command you can do exactly that:
Now you can just type search instead of grep at your Linux command line:
In another simple alias example, instead of always typing this ls command to get a directory listing:
I’ve created an alias so I only have to type the lowercase letter «L» like this:
Whenever I use this alias, it’s exactly the same as if I had typed out the longer ls -al Linux command.
Using aliases like this you can create anything from simple shortcuts like this to powerful custom commands.
How to define a Linux alias
Creating a Linux alias is very easy. You can either enter them at the command line as you’re working, or more likely, you’ll put them in one of your startup files, like your .bash_profile or .bashrc files, so they will be available every time you log in.
I created the l alias above by entering the following command into my .bash_profile file:
As you can see, the Linux alias syntax is very easy:
- Start with the alias command
- Then type the name of the alias you want to create
- Then an = sign, with no spaces on either side of the =
- Then type the command (or commands) you want your alias to execute when it is run. This can be a simple command, or can be a powerful combination of commands.
Unix/Linux alias examples and syntax
To get you going, here is a list of sample Linux aliases I use all the time. I’ve pretty much just copied them here from my .bashrc file:
As you can see, you can get as creative as you want, and pipe commands together to do just about anything. In the last alias shown I’ve actually combined three Linux commands in a row into one alias to get the output I want.
Because the Unix shell is very programmable and because the output of commands is very consistent and reliable, you can create your own aliases (or macros if you prefer) to do just about anything.
Have a favorite Linux alias?
If you have a favorite Linux alias command/example you’d like to share, feel free to leave it in the comments section below.
Источник
Using alias Command in Linux to Improve Your Efficiency
As it is known, Linux and Unix were created as command line based systems, which means having control of the commands typed is basically the most important thing to be a *nix SysOp.
This is where ‘alias’ command comes to the show and can be extremely useful, especially for security purposes and to simplify work for a system administrator.
Linux alias command
The shell alias is simply a way to reference another command. It can be used to avoid repetitive long typing of commands and shell lines and simplify work or to even make things safer or dumb-proof.
Take a simple example where you have to use ls command to show everything in reverse chronological order. You can type ls -lrta all the time or you create an alias (say) ‘ll’ that will be equivalent to ls -lrta. It will save you a few keystrokes.
In a similar fashion, you can substitute long and complicated commands with small and simple commands by using alias in Linux.
Let’s see how to make alias in Linux.
How to create alias in Linux
I’ll continue with the same example I used above.
You must note a few things:
- The substituted command is always used under the inverted commas (‘).
- There must be no spaces before or after the equals sign in the alias command. If you mistakenly put a space, you’ll see an error like alias not found.
- Be careful in choosing the name of the alias. There are no reserved keywords so you may replace an existing command with a totally irrelevant command.
You can check if a certain command is actually an alias with the type command. For example, in Ubuntu, ls is actually an alias to show you colorful output.
If you want to use the original command, without its aliased version, use single quotes around it.
Now, the alias you just is temporary. If you exit the shell, you’ll lose the alias. You need to make the alias permanent.
Make alias permanent
In order to add aliases that can work in a system all the time, you need to simply edit your user’s (or any other user’s) .bashrc file. Some distributions might suggest using a dedicated .bash_aliases file for storing aliases.
This file is located in your /home/ / folder. You can use vim command to edit the file in terminal.
This will immediately open your .bashrc file and you must start adding aliases by the end of the file, just after the last written line of it. You should then source the bashrc file.
I suggest creating either blocks or at least adding commentaries in the file for each of the aliases created so it’s easier in the future to know what is each thing for maintenance purposes.
Creating global aliases for all users
If you want the aliases to be available for all users on your Linux system, you should add the aliases in /etc/bash.bashrc file.
If you don’t have this file, create it.
How to see all the alias set on your Linux system for you
If you want to see all the alias set on the system for you, you can check the configuration file of your shell like
However, a much easier way to see all the alias would be to simply run the alias command without any arguments.
A typically Ubuntu system has the following alias set by default.
How to remove alias
If you want to remove an alias, you can use the unalias command in this manner:
You can remove all alias at once using the -a option:
As with the alias command, changes by unalias command are also temporary. If you wan to remove an alias permanently, you should delete it from the bashrc file.
My favorite alias in Linux I cannot live without
Let me share some aliases that I always use to work more effectively in Linux.
1. Making ‘rm’ safer
As it is well known, rm command is very commonly used day by day and can be also very destructive and disruptive of a system if not properly used.
This is why, I use the following alias:
This makes ‘rm’ command safer as whenever you use it, it will always ask if you are sure you want to perform the infamous removal operation before proceeding, giving you a second and last chance to not break things unintentionally.
2. Making ssh to other systems easier and faster
Sometimes, especially if you use private keys instead of credentials to log in to other Linux systems, it can be easier to set up aliases for each of them with mnemonic names.
As a SysOp, I use SSH for logging in to different Linux servers and I have several private keys, depending on my clients, therefore it helps me to have aliases such as:
As you can see, I have all my private keys in a folder named “SSH-keys” inside my own user’s folder and then I simply create aliases to connect each of them, following a standard of “ssh”+”name of the server”.
This way I only have to remember the name of the server I want to connect and not where the key is located, the name of each key (if they are different) or even the username that needs to be used for each server to connect.
3. Show time or date for day to day things
Some people either because they script things that use specific times or need to consult time and/or date and want to have in specific formats, can get some benefit of aliases by doing:
4. Easily manage your iptables information
Let’s face it: iptables or nftables are not the easiest nor friendly thing in the world and even though it’s not hard, the first time you deal with it is not that easy. This is why using aliases such these ones can make things a lot easier:
5. Update Debian based servers in one single command
I use Ubuntu myself, but you can adapt this for any Red Hat, CentOS servers and ‘yum’ command. On Debian/Ubuntu, updating a server in a single command could be done through an alias such as this one:
6. Add an alias to run alias with sudo
You cannot run an alias with sudo by default. If you want to run an aliased command with root access, you’ll have to create an alias with sudo like this:
Conclusion
As you can see, it all depends on what you do and your creativity, but you can basically take the time to create as many aliases as you need for your day to day tasks and make them easier by using this useful ‘alias’ command in Linux.
Источник