sudo и alias в .bashrc
Недавно в гостях у друга увидел книгу Скотта Граннемана «Linux. Карманный справочник» и выпросил ее почитать. И хотя Linux уже два года красуется на моем компьютере, я далеко не в совершенстве знаю команды командной строки (извиняюсь за тавтологию).
Вообще то еще на третьем курсе университета у нас был курс Unix, который мне очень нравился, и на котором я смог оценить мощь и силу командной строки unix‘подобных систем. К сожалению тогда у меня был только dialup, да и кодить приходилось в основном на Delphi, поэтому переход на Linux (Mandrake) не задался, а очень жаль.
alias
Что то я отвлекся от темы поста. Вычитал я в книге значит несколько интересных моментов и тут же решил попробовать. Во первых это назначение в ~/.bashrc alias‘ов для команд. Первым делом я назначил alias для команды ls, частенько я ей пользуюсь и почти на автомате вбиваю ls -l. Из той же книги я узнал что полезно указать еще параметр h, для более наглядного отображения размеров файлов, и вот что у меня получилось:
alias l=’ls -lh’
Казалось бы ничего особенного, но удобно блин.
sudo
Дальше я дочитал до способов объединения команд, и нашел интересный пример:
apt-get update && apt-get upgrade
Основная идея данной записи — выполнить обновление системы в случае удачного обновления списка пакетов. Так как сейчас у меня стоит бета Ubuntu 10.04 то обновляюсь я каждый день, поэтому решил добавить еще один alias:
alias uu=’apt-get update && apt-get upgrade’
Перезапускаю терминал, sudo uu, а он мне в ответ мол не знаю я команды uu. Не долго думая добавляю аналогичный alias в /root/.bashrc.
Перезапускаю терминал, sudo uu, а он мне опять тоже самое. И тут я задумался, а кто же ты тогда sudo?
Немного поразмыслив решил спросить у google, на что сразу получил несколько ответов, но не один у меня так и не заработал. Если кому интересно, предлагалось добавить alias в глобальный файл /etc/bash.bashrc, а так же вызывать sudo -E.
Простое и действенное решение подсказал знакомый гуру Linuxa — medvoodoo.
sudo — команда а alias‘ы обрабатывает сам bash, поэтому sudo не может понять чего от нее хотят. (Здесь я могу ошибаться, можете поправить меня в комментариях).
В результате мой alias uu выглядит следующим образом:
alias uu=’sudo apt-get update && sudo apt-get upgrade -y’
Надеюсь эта информация будет кому-то инересной/полезной.
P.S. Поздравляю всех с праздником Великой Пасхи и с днем 4.04.
Aliases in .bashrc
It can be useful to backup the ~/.bashrc before editing it, as it allows one to be able to easily recover from the unexpected. To make a backup of your current .bashrc . Open a terminal and execute:
The original .bashrc can be restored with by executing
Any changes made to the ~/.bashrc will have no effect on any currently open terminal windows. To test newly updated changes in your ~/.bashrc open a new terminal or use the command:
Aliases can turn a complex command string into a simple custom made command that one can type in the Terminal.
Standard syntax
Creating aliases in bash is very straight forward. The syntax is as follows:
. alias alias_name="command_to_run" .
For updating your system
To upgrade the system via pacman, the command used is
This can be aliased in ~/.bashrc with
. alias pacup="sudo pacman -Syu" .
To upgrade packages installed from the AUR via pamac, the command used is
. alias aup="pamac upgrade --aur" .
For editing commonly used files
To edit ~/.bashrc itself and automatically reload bash configuration file (so that changes made to .bashrc can be implemented in current terminal session)
. alias bashrc="nano ~/.bashrc && source ~/.bashrc" .
. alias fstab="sudo nano /etc/fstab" .
To edit /etc/default/grub
. alias grub="sudo nano /etc/default/grub" .
To update GRUB
To update your grub bootloader using the sudo update-grub
. alias grubup="sudo update-grub" .
Sometimes you may need to create an alias that accepts one or more arguments. That’s where bash functions come in handy.
The syntax for creating a bash function is very easy. They can be declared in two different formats:
To pass any number of arguments to the bash function simply, put them right after the function’s name, separated by a space. The passed parameters are $1, $2, $3, etc., corresponding to the position of the parameter after the function’s name. The $0 variable is reserved for the function name.
Let’s create a simple bash function which will create a directory and then navigate into it:
Now instead of using mkdir to create a new directory and then cd to move into that directory , you can simply type:
Bash allows you to add local aliases in your ~/.bashrc file. To do this create a file called ~/.bash_aliases and add these contents in your ~/.bashrc file:
. if [ -e $HOME/.bash_aliases ]; then source $HOME/.bash_aliases fi .
Now you can add any aliases in your ~/.bash_aliases file and then load them into your Bash session with the source ~/.bashrc command.
This list is not comprehensive. Almost anything that is commonly used can be shortened with an alias
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:
$ type -a alias alias is a shell builtin
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.
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.
$ ls -la ~ | grep -i .bash_aliases # Check if file is available $ touch ~/.bash_aliases # Create empty alias 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.
# Alias definitions. # You may want to put all your additions into a separate file like # ~/.bash_aliases, instead of adding them here directly. # See /usr/share/doc/bash-doc/examples in the bash-doc package. if [ -f ~/.bash_aliases ]; then . ~/.bash_aliases fi
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.
# enable color support of ls and also add handy aliases if [ -x /usr/bin/dircolors ]; then test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)" alias ls='ls --color=auto' #alias dir='dir --color=auto' #alias vdir='vdir --color=auto' alias grep='grep --color=auto' alias fgrep='fgrep --color=auto' alias egrep='egrep --color=auto' fi # colored GCC warnings and errors #export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01' # some more ls aliases alias ll='ls -alF' alias la='ls -A' alias l='ls -CF' # Add an "alert" alias for long running commands. Use like so: # sleep 10; alert alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*2\+\s*//;s/[;&|]\s*alert$//'\'')"'
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.
$ alias Hello"echo welcome to Tecmint" $ alias $ Hello
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.
$ echo alias nf="neofetch" >> ~/.bash_aliases $ cat >> ~/.bash_aliases $ cat ~/.bash_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.
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.
$ uptime $ cat >> ~/.bash_aliases alias uptime="echo 'I am running uptime command now'" $ source ~/.bash_aliases $ uptime
From this example, you can conclude the precedence falls to bash aliases before checking and invoking the actual command.
$ cat ~/.bash_aliases $ source ~/.bash_aliases $ uptime
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.
NOTE: Unalias will remove the alias definition from the currently loaded session, not from .bashrc or .bash_aliases.
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.
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.
$ sudo cat >> /etc/profile.d/alias.sh alias ls=”ls -ltra”
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.
NOTE: It is best practice to take a backup of user-level or system-level files. If in case something went wrong backup copy can be reverted.
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.