Alias linux bash script

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

Создание алиасов в оболочке Bash

Алиасы это.

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

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

Создание временных алисов

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

Для создания временного алиаса выполните в терминале команду — alias [name]=»[command]» , где [name] — имя алиаса, а [command] — команда, которую вы хотите выполнить с помощью алиаса.

Для примера давайте создадим простой алиас команды перехода в корневой каталог:

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

Теперь для того чтобы выполнить переход в корневой каталог достаточно выполнить в консоли команду — g :

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

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

/.bashrc , который представляет собой обычный bash-скрипт исполняемый каждый раз при открытии терминала.

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

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

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

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

Однако сразу после сохранения алиас работать не будет, так как для применения новых настроек нужно заново выполнить файл

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

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

Важно чтобы рядом со знаком — = не было пробелов, т.е. такая запись недопустима — alias g = ‘cd /’

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

Удаление алиасов

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

Чтобы удалить постоянный алиас нужно всего лишь удалить соответствующую строку в файле

/.bash_aliases , в зависимости от того где он находится. Затем перезагрузить консоль или выполнить обновление настроек следующей командой:

Создание отдельного файла для алиасов

Для того чтобы уменьшить риск работы с файлом

/.bashrc , и просто для удобства — можно создать отдельный файл

Читайте также:  Как выбрать загрузочный диск при запуске windows

/.bash_aliases , в котором будут храниться все ваши алиасы.

Для этого убедитесь, что в файле

/.bashrc есть код данный ниже, если же его нет то просто вставьте его в конец файла.

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

После обновляем файл

/.bashrc и наши алиасы готовы к постоянному использованию.

Если вы хотите чтобы ваш список алиасов был доступен не только вам, но и всем пользователям системы, то в таком случае этот список нужно добавить в каталог /etc/profile.d с расширением .sh .

Скопируем наш файл с алиасами в каталог /etc/profile.d не забыв указать расширение .sh .

Созданный файл aliases.sh будет читаться системой при каждом запуске оболочки BASH. Чтобы изменения вступили в силу нужно перезапустить оболочку.

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

Как временно отключить работу алиаса?

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

Допустим есть алиас, в котором команда free вызывается с флагами:

alias free=’free -th’

Но нам нужно вызвать команду free без флагов, в таком случае поставьте перед free обратный слэш.

Список полезных алиасов для CentOS и Ubuntu

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

/.bashrc или лучше в

/.bash_aliases . Знаком — # обозначены комментарии.

# Файлы
alias sl=»ls»
alias ll=»ls -lah» # Показать скрытые файлы с читаемыми размерами
alias l.=»ls -d .*» # Показать только скрытые файлы и папки
alias lf=»ls -p | grep -v /» # Показать только файлы
alias ld=»ls -d */» # Показать только директории
alias lt=»ls -lhart» # Сортировать по времени
alias lz=»ls -AFlSr» # Сортировать по размеру
alias t=»touch»
alias ff=»find . -type f -iname» # Найти файл по имени в текущей папке
alias catc=’clear && grep -v -e «^$» -e»^ *#»‘ # Показать файл с кодом без коментариев

# Директории
alias md=»mkdir -pv»
alias fd=’find . -type d -name’ # Найти директорию по имени в текущей папке
alias ..=»cd ..»
alias . =»cd ../..»
alias .3=»cd ../../..»
alias .4=»cd ../../../..»
alias g=»cd /»
alias w=»cd /var/www»
alias bscript=»cd /usr/local/sbin && ls» # Показать список своих Bash-скриптов
alias ngsa=»cd /etc/nginx/sites-enabled && ls» # Показать список доступных сайтов в nginx
cds () < cd /var/www/"$1"/www && ls -a; ># Перейти в директорию сайта (cds meliorem.ru)

# Архивы
alias tarc=»tar czvf» # Создать архив
alias tarx=»tar xzvf» # Извлечь архив
alias tart=»tar tzvf» # Показать содержимое архива

# Подтверждение действий
alias mv=»mv -iv»
alias cp=»cp -iv»
alias ln=»sudo ln -iv»
alias rm=»sudo rm -riv»
alias rmf=»sudo rm -rfiv» # Принудительное удаление

# Обновление Bash-файлов
alias bau=».

/.bash_aliases»
alias bpu=».

/.bash_profile»
alias bru=».

# Менеджер пакетов Apt (Ubuntu)
alias ag=»sudo apt-get»
alias agi=»sudo apt-get install»
alias agyi=»sudo apt-get -y install»
alias agu=»sudo apt-get update»
alias agr=»sudo apt-get remove»
alias acs=»apt-cache search»

# Менеджер пакетов Yum (CentOS)
alias yum=»sudo yum»
alias yi=»sudo yum install»
alias yyi=»sudo yum -y install»
alias yu=»sudo yum update»
alias yr=»sudo yum remove»
alias ys=»yum search»
alias yp=»yum provides»

# Vi/Vim
alias vim=»sudo vim»
alias vi=»sudo vi»
alias vimalias=»sudo vim

/.bash_aliases»
alias vimbashrc=»sudo vim

/.bashrc»
alias vimprofile=»sudo vim

/.bash_profile»
alias vimphp=»sudo vim /etc/php/7.0/fpm/php.ini» # ! Сначала найдите свой php.ini !
alias vimnginx=»sudo vim /etc/nginx/nginx.conf && nginx -t»
alias vimhttpd=»sudo vim /etc/httpd/conf/httpd.conf && systemctl httpd configtest»
alias vimmy=»sudo vim /etc/my.cnf»

# Systemctl
alias sc=»systemctl»
alias scsts=»clear && systemctl status» # (scsts nginx)
alias scstt=»systemctl start»
alias screl=»systemctl reload»
alias scrst=»systemctl restart»
alias scstp=»systemctl stop»
alias scen=»systemctl enable»
alias scisen=»systemctl is-enabled»
alias scdis=»systemctl disable»
alias sclist=»systemctl list-unit-files | less» # Список служб

# System info
alias df=»df -hPT | column -t» # Память диска
alias free=»free -mth» # RAM
alias path=»echo $PATH | tr ‘:’ ‘\n’ | nl» # Удобный вывод $PATH

# Network
alias ping=»ping -c4″
alias ports=»netstat -tulanp» # Показать открытые порты
alias ipinfo=»curl ifconfig.me && curl ifconfig.me/host» # Показать свой IP и Hostname

# Сокращения
alias q=»exit»
alias s=»sudo»
alias c=»clear»
alias a=»clear && alias | less» # Показать список алиасов
alias ag=»alias | grep» # Если помнишь только часть имени алиаса

# Extra
alias ax=»chmod a+x» # Сделать файлы исполняемым
alias upload=»sftp username@server.com:/path/to/upload/directory»

# Загрузить этот список алиасов в свой

/.bash_aliases
alias baload=»wget -P

# FUNCTIONS
cls () < cd $@ && ls -a; >
mcd () < sudo mkdir -p "$1"; cd "$1";># Создать директорию и войти в неё (mcd

/music/classic)
backup () < sudo cp "$1"<,.backup>;> # Создать копию файла в текущей папке
newbs () < cd /usr/local/sbin && sudo touch "$1" && sudo chmod a+x "$1" && sudo vim "$1"; ># Новый Bash скрипт
psgrep () <
if [ ! -z $1 ] ; then
echo «Grepping for processes matching $1. »
ps aux | grep $1 | grep -v grep
else
echo «!! Need name to grep for»
fi
>

Читайте также:  Windows crashes after update

# 🙂
alias hacker=’cat /dev/urandom | hexdump -C | grep «ca fe»‘ # Кулл хацкер

Понравилась статья? Расскажите о ней друзьям!

Источник

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:

#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:

Читайте также:  Windows terminal служба сенсорной клавиатуры

#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

Источник

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