Aliases in linux bash

Содержание
  1. Создание синонимов команд в Linux. Команда alias
  2. Создание синонимов (команда alias)
  3. Синтаксис команды alias
  4. Примеры создания синонимов
  5. Сохранение синонимов
  6. Просмотр списка синонимов
  7. Удаление синонимов
  8. Несколько примеров синонимов
  9. Создание синонимов, используя Bash-функции (синонимы с аргументами)
  10. Синтаксис функций в Bash
  11. Примеры создания функций
  12. Заключение
  13. Different Ways to Create and Use Bash Aliases in Linux
  14. Check Bash Aliases in Linux
  15. Creating Alias in Linux
  16. Removing an Alias in Linux
  17. Adding System-Wide Aliases
  18. If You Appreciate What We Do Here On TecMint, You Should Consider:
  19. 30 Handy Bash Shell Aliases For Linux / Unix / MacOS
  20. More about bash shell aliases
  21. How to list bash aliases
  22. How to define or create a bash shell alias
  23. How to disable a bash alias temporarily
  24. How to delete/remove a bash alias
  25. How to make bash shell aliases permanent
  26. A note about privileged access
  27. A note about os specific aliases
  28. 30 bash shell aliases examples
  29. #1: Control ls command output
  30. #2: Control cd command behavior
  31. #3: Control grep command output
  32. #4: Start calculator with math support
  33. #4: Generate sha1 digest
  34. #5: Create parent directories on demand
  35. #6: Colorize diff output
  36. #7: Make mount command output pretty and human readable format
  37. #8: Command short cuts to save time
  38. #9: Create a new set of commands
  39. #10: Set vim as default
  40. #11: Control output of networking tool called ping
  41. #12: Show open ports
  42. #13: Wakeup sleeping servers
  43. #14: Control firewall (iptables) output
  44. #15: Debug web server / cdn problems with curl
  45. #16: Add safety nets
  46. #17: Update Debian Linux server
  47. #18: Update RHEL / CentOS / Fedora Linux server
  48. #19: Tune sudo and su
  49. #20: Pass halt/reboot via sudo
  50. #21: Control web servers
  51. #22: Alias into our backup stuff
  52. #23: Desktop specific – play avi/mp3 files on demand
  53. #24: Set default interfaces for sys admin related commands
  54. #25: Get system memory, cpu usage, and gpu memory info quickly
  55. #26: Control Home Router
  56. #27 Resume wget by default
  57. #28 Use different browser for testing website
  58. #29: A note about ssh alias
  59. #30: It’s your turn to share…
  60. Conclusion
  61. Conclusion

Создание синонимов команд в 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 подумала бы, что мы пытаемся передать ей не имя директории а опцию.
  • && — логическое И — сначала выполняется команда, стоящая слева от && и только если она выполнена успешно, запускается команда, стоящая справа от && .
Читайте также:  Во что отформатировать внешний диск mac windows

Заключение

Синонимы команд в Linux очень удобный инструмент, упрощающий работу с системой. В данной статье мы рассмотрели создание синонимов командой alias , а также использование функций Bash для создания синонимов.

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

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

Источник

Different Ways to Create and Use Bash Aliases in Linux

Alias in bash can be termed simply as a command or a shortcut that will run another command/program. Alias is very helpful when our command is very long and for frequently used commands. Over the course of this article, we are going to see how powerful is an alias and the different ways to set up an alias and use it.

Check Bash Aliases in Linux

Alias is a shell builtin command and you can confirm it by running:

Before jumping and setting up an alias we will see the configuration files involved. An alias can be set either at the “user-level” or “system level”.

Invoke your shell and simply type “alias” to see the list of defined alias.

Check List of Defined Linux Aliases

User-level aliases can be defined either in the .bashrc file or the .bash_aliases file. The .bash_aliases file is to group all your aliases into a separate file instead of putting it in the .bashrc file along with other parameters. Initially, .bash_aliases will not be available and we have to create it.

Create Bash Aliases File

Open the .bashrc file and look out for the following section. This section of code is responsible for checking if file .bash_aliases is present under the user home directory and load it whenever you initiate a new terminal session.

Bashrc Alias Definition

You can also create a custom alias file under any directory and add definition in either .bashrc or .profile to load it. But I will not prefer this and I choose to stick with grouping all my alias under .bash_aliases.

You can also add aliases under the .bashrc file. Look out for the alias section under the .bashrc file where it comes with some predefined aliases.

Bashrc Defined Aliases

Creating Alias in Linux

You can either create a temporary alias that will be stored only for your current session and will be destroyed once your current session ends or permanent alias which will be persistent.

The syntax for creating an alias in Linux.

For example, in a real scenario.

Open the terminal and create any alias command you desire. If you open another session then the newly created alias will not be available.

Create an Alias in Linux

To make the alias persistent, add it to the .bash_aliases file. You can use your favorite text editor or use the cat command or echo command to add an alias.

List Defined Aliases

You have to reload the .bash_aliases file for the changes to be effective in the current session.

Now if I run “nf” which is an alias for “neofetch” it will trigger the neofetch program.

Run Alias in Linux

An alias can come in handy if you wish to override the default behavior of any command. For demonstration, I will take an uptime command, that will display system uptime, the number of users logged in, and the system load average. Now I will create an alias that will override the behavior of the uptime command.

Override Default Behaviour of Command

From this example, you can conclude the precedence falls to bash aliases before checking and invoking the actual command.

Unchanged Command Behaviour

Removing an Alias in Linux

Now remove the uptime entry from the .bash_aliases file and reload the .bash_aliases file which will still print the uptime with alias definition. This is because the alias definition is loaded into the current shell session and we have to either start a new session or unset the alias definition by running the unalias command as shown in the below image.

Remove an Alias in Linux

Adding System-Wide Aliases

Till this point, we have seen how to set up an alias at the user level. To set an alias globally you can modify the “/etc/bash.bashrc” file and add aliases which will be effective globally. You need to have the elevated privilege to modify bash.bashrc file.

Читайте также:  Вызов калькулятора горячие клавиши windows 10

Alternatively, create a script under “/etc/profile.d/”. When you log in to a shell “/etc/profile” will run any script under profile.d before actually running

/.profile. This method will reduce the risk of messing up either /etc/profile or /etc/bash.bashrc file.

Below is the code grabbed from the /etc/profile that takes care of running any scripts that we put under /etc/profiles.d/. It will look out for any files with the .sh extension and run the source command.

Global Profile File

That’s it for this article. We have seen what is alias, the configuration files involved with the alias, and different ways to set up the alias locally and globally.

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.

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.

Источник

30 Handy Bash Shell Aliases For Linux / Unix / MacOS

A n bash shell alias is nothing but the shortcut to commands. The alias command allows the user to launch any command or group of commands (including options and filenames) by entering a single word. Use alias command to display a list of all defined aliases. You can add user-defined aliases to

/.bashrc file. You can cut down typing time with these aliases, work smartly, and increase productivity at the command prompt.

This post shows how to create and use aliases including 30 practical examples of bash shell aliases.

More about bash shell aliases

The general syntax for the alias command for the bash shell is as follows:

How to list bash aliases

Type the following alias command:
alias
Sample outputs:

By default alias command shows a list of aliases that are defined for the current user.

How to define or create a bash shell alias

To create the alias use the following syntax:

In this example, create the alias c for the commonly used clear command, which clears the screen, by typing the following command and then pressing the ENTER key:

Then, to clear the screen, instead of typing clear, you would only have to type the letter ‘c’ and press the [ENTER] key:

How to disable a bash alias temporarily

How to delete/remove a bash alias

You need to use the command called unalias to remove aliases. Its syntax is as follows:

In this example, remove the alias c which was created in an earlier example:

You also need to delete the alias from the

/.bashrc file using a text editor (see next section).

How to make bash shell aliases permanent

The alias c remains in effect only during the current login session. Once you logs out or reboot the system the alias c will be gone. To avoid this problem, add alias to your

The alias c for the current user can be made permanent by entering the following line:

Save and close the file. System-wide aliases (i.e. aliases for all users) can be put in the /etc/bashrc file. Please note that the alias command is built into a various shells including ksh, tcsh/csh, ash, bash and others.

A note about privileged access

You can add code as follows in

A note about os specific aliases

You can add code as follows in

30 bash shell aliases examples

You can define various types aliases as follows to save time and increase productivity.

#1: Control ls command output

The ls command lists directory contents and you can colorize the output:

#2: Control cd command behavior

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

#3: Control grep command output

grep command is a command-line utility for searching plain-text files for lines matching a regular expression:

#4: Start calculator with math support

#4: Generate sha1 digest

#5: Create parent directories on demand

mkdir command is used to create a directory:

#6: Colorize diff output

You can compare files line by line using diff and use a tool called colordiff to colorize diff output:

#7: Make mount command output pretty and human readable format

#8: Command short cuts to save time

#9: Create a new set of commands

#10: Set vim as default

#11: Control output of networking tool called ping

#12: Show open ports

Use netstat command to quickly list all TCP/UDP port on the server:

#13: Wakeup sleeping servers

Wake-on-LAN (WOL) is an Ethernet networking standard that allows a server to be turned on by a network message. You can quickly wakeup nas devices and server using the following aliases:

Читайте также:  Активация windows professional oem

#14: Control firewall (iptables) output

Netfilter is a host-based firewall for Linux operating systems. It is included as part of the Linux distribution and it is activated by default. This post list most common iptables solutions required by a new Linux user to secure his or her Linux operating system from intruders.

#15: Debug web server / cdn problems with curl

#16: Add safety nets

#17: Update Debian Linux server

apt-get command is used for installing packages over the internet (ftp or http). You can also upgrade all packages in a single operations:

#18: Update RHEL / CentOS / Fedora Linux server

yum command is a package management tool for RHEL / CentOS / Fedora Linux and friends:

#19: Tune sudo and su

#20: Pass halt/reboot via sudo

shutdown command bring the Linux / Unix system down:

#21: Control web servers

#22: Alias into our backup stuff

#23: Desktop specific – play avi/mp3 files on demand

vnstat is console-based network traffic monitor. dnstop is console tool to analyze DNS traffic. tcptrack and iftop commands displays information about TCP/UDP connections it sees on a network interface and display bandwidth usage on an interface by host respectively.

#25: Get system memory, cpu usage, and gpu memory info quickly

#26: Control Home Router

The curl command can be used to reboot Linksys routers.

#27 Resume wget by default

The GNU Wget is a free utility for non-interactive download of files from the Web. It supports HTTP, HTTPS, and FTP protocols, and it can resume downloads too:

#28 Use different browser for testing website

#29: A note about ssh alias

Do not create ssh alias, instead use

/.ssh/config OpenSSH SSH client configuration files. It offers more option. An example:

You can now connect to peer1 using the following syntax:
$ ssh server10

#30: It’s your turn to share…

Conclusion

This post summarizes several types of uses for *nix bash aliases:

  1. Setting default options for a command (e.g. set eth0 as default option for ethtool command via alias ethtool=’ethtool eth0′ ).
  2. Correcting typos (cd.. will act as cd .. via alias cd..=’cd ..’ ).
  3. Reducing the amount of typing.
  4. Setting the default path of a command that exists in several versions on a system (e.g. GNU/grep is located at /usr/local/bin/grep and Unix grep is located at /bin/grep. To use GNU grep use alias grep=’/usr/local/bin/grep’ ).
  5. Adding the safety nets to Unix by making commands interactive by setting default options. (e.g. rm, mv, and other commands).
  6. Compatibility by creating commands for older operating systems such as MS-DOS or other Unix like operating systems (e.g. alias del=rm ).

I’ve shared my aliases that I used over the years to reduce the need for repetitive command line typing. If you know and use any other bash/ksh/csh aliases that can reduce typing, share below in the comments.

Conclusion

I hope you enjoyed my collection of bash shell aliases. See

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

Nice list; found a couple new things I never thought of. To return the favor; my addon..

A nice shell is key in bash imo; I color code my next line based on previous commands return code..

And I liked your . <1,2,3,4>mapping; how I integrated it…

And two random quick short ones..

The following is my version of the “up function” I came up with this morning:

Show text file without comment (#) lines (Nice alias for /etc files which have tons of comments like /etc/squid.conf)

@linuxnetzer, nocommand is nice to dump squid, httpd and many others config files.

@mchris, I liked cp alias that can show progress.

Appreciate your comments.

Ctrl+L is also a nice quick way to clear the terminal.

Hi!
This isn’t an alias, but for clear screen is very handy the CTRL+L xDD

Источник

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