alias command in Linux with Examples


Advertisements

Name

alias - instruct the shell to replace one string with another, while executing the commands.

Synopsis

alias [-p] [name[=value] ... ]

Options

-p
   print all defined aliases in a reusable format 
-a
   Remove All aliases
--help
   It displayes help Information. 

Description

alias are like custom shortcuts used to represent a command (or set of commands) executed with or without custom options. It is like a shortcut command which will have same functionality as if we are writing the whole command.

Without arguments, alias prints the list of aliases in the reusable form alias NAME=VALUE on standard output. Otherwise, an alias is defined for each NAME whose VALUE is given. A trailing space in VALUE causes the next word to be checked for alias substitution when the alias is expanded.

Examples

1. The syntax for creating an alias is: alias name="value"

$ alias .=cd

In the above command we have created an alias for 'cd' command which is use for change the directory.

2. To see all defined aliases in a reusable format, we can use the -p option.

$ alias -p
alias .='cd'
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'
alias grep='grep --color=auto'
alias l='ls -CF'
alias la='ls -A'
alias ll='ls -alF'
alias ls='ls --color=auto'

Setting an alias in this way only works for the life of a shell session. When the shell is closed the alias will be lost.

3. To make an alias persist across shell sessions and reboots a configuration file for the shell should be used. For bash this is the .bashrc file. If you are using zsh it is the .zshrc file.

4. The following are some practical examples of using aliases in .bashrc file.

$ ensure git commits are signed
alias git commit='git commit -S'

$ shorthand for vim
alias vi="vim"

# setting preferred options on ls
alias ls='ls -lhF' 

# prompt user if overwriting during copy
alias cp='cp -i'

# prompt user when deleting a file
alias rm='rm -i'

# always print in human readable form
alias df="df -h"

# always use vim in place of vi
alias vi=vim

5. We can remove an alias by using the unailas command.

syntax: unalias [alias name]

$ alias vi
alias vi='vim'
$ unalias vi
$ alias vi
bash: alias: vi: not found    

We see above that vi was alias to vim. After unalias command vi does not refer to any command.

Advertisements