Alias in shell refers to giving another name to a command or group of commands. It is very useful when a name of a command is long. With the help of alias, we can avoid typing a bigger name and invoke a command by a name as per your convenience.
To create an alias, alias shell builtin command is used. The syntax is as follows:
alias alias_name="Commands to be aliased"
To print a disk space in a human-readable format, we use the df
command with the -h
option. By making alias of df -h
to df
, we can avoid typing again and again df -h
.
The output of the df
command before aliasing it to df -h
is shown in the following screenshot:
$ df
Now, to create alias for df -h to df, we will execute the following command:
$ alias df="df -h" # Creating alias $ df
The output obtained is as follows:
We see that after creating alias of df -h
to df
, a default disk space is printed in a human-readable format.
Another useful example can be aliasing the rm
command to rm -i
. Using rm
with the -i
option asks the user for a confirmation before deleting them:
#!/bin/bash # Filename: alias.sh # Description: Creating alias of rm -i touch /tmp/file.txt rm /tmp/file.txt # File gets deleted silently touch /tmp/file.txt # Creating again a file alias rm="rm -i" # Creating alias of rm -i rm /tmp/file.txt
The output after executing the preceding script is as follows:
rm: remove regular empty file '/tmp/file.txt'? Y
We can see that after alias creation, rm
asks for a confirmation before deleting the /tmp/file.txt
file.
To see the aliases that are already set for the current shell, use an alias without any argument or with the –p
option:
$ alias alias df='df -h' alias egrep='egrep --color=auto' alias fgrep='fgrep --color=auto' alias grep='grep --color=auto' alias l.='ls -d .* --color=auto' alias ll='ls -l --color=auto' alias ls='ls --color=auto' alias vi='vim'
We can see that the df
alias that we created still exists, along with the already other existing aliases.
To remove an already existing alias, we can use the unalias
shell builtin command:
$ unalias df # Deletes df alias $ alias -p # Printing existing aliases alias egrep='egrep --color=auto' alias fgrep='fgrep --color=auto' alias grep='grep --color=auto' alias l.='ls -d .* --color=auto' alias ll='ls -l --color=auto' alias ls='ls --color=auto' alias vi='vim'
We see that the df
alias has been removed. To remove all aliases, use unalias
with the a
option:
$ unalias -a # Delets all aliases for current shell $ alias -p
We can see that all aliases have now been deleted.
3.136.234.127