Friday, November 20, 2020

Create permanent BASH aliases in Linux

When creating an alias, for example
alias la="ls -la"
it exists until the terminal session is killed. When starting a new terminal window, the alias does not exist any more. The question is, how to create a "permanent" alias, one that exists in every terminal session?
Such aliases can be stored in the ~/.bash_aliases file.
 
That file is loaded by ~/.bashrc. The following lines need to be uncommented or added to enable the use of the ~/.bash_aliases file:

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

 
The aliased command will be available on any new terminal. To have the aliased command on any existing terminal one need to source ~/.bashrc from that terminal:
source ~/.bashrc

A one liner would be:
echo "alias la='ls-la'" >> ~/.bash_aliases && source ~/.bash_aliases
 
Another option would be to add the alias line into ~/.bashrc or into ~/.profile / ~/.bash_profile for remote logins. If the command should be executed for all users, put it into /etc/bash.bashrc.
 
The function below can be added to the .bashrc file.
function permalias () 
{ 
  alias "$*";
  echo alias "$*" >> ~/.bash_aliases
}
Then open a new terminal or run source ~/.bashrc in your current terminal. You can now create permanent aliases by using the permalias command, for example permalias cls=clear.

~/.bashrc is run every time you open a new terminal, whereas ~/.bash_profile is not.

In order to update the file, run . ~/.bashrc or source ~/.bashrc

Function from askubuntu.com:

# -----------------------------------
#  Create a new permanent bash alias
#
#  @param $1 - NAME
#  @param $2 - DEFINITION
# -----------------------------------
new-alias () { 
  if [ -z "$1" ]; then
    echo "alias name:" && read NAME
  else
    NAME=$1
  fi

  if alias $NAME 2 > /dev/null > /dev/null; then
    echo "alias $NAME already exists - continue [y/n]?" && read YN
    case $YN in
      [Yy]* ) echo "okay, let's proceed.";;
      [Nn]* ) return;;
      * ) echo "invalid response." && return;;
    esac
  fi

  if [ -z "$2" ]; then
    echo "alias definition:" && read DEFINITION
  else
    DEFINITION="$2"
  fi

  if [ -f ~/.bash_aliases ]; then
    echo "alias $NAME=\"$DEFINITION\"" >> ~/.bash_aliases
  else
    echo "alias $NAME=\"$DEFINITION\"" >> ~/.bashrc
  fi

  alias $NAME="$DEFINITION"
}