Putting Aliases in the .bash_aliases File

I was doing some more poking around in the .bashrc file in my home folder, and I spotted these three lines.

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

What these lines do is look in my home folder for a file called .bash_aliases. If it is found, the file is opened and the contents are read in. Effectively it makes the contents of the .bash_aliases file appear to be part of the .bashrc file.

Because the .bashrc file is executed each time you open a terminal window, anything you put in the .bash_aliases file is executed as well. And as the name implies, the idea is that you put your personal alias definitions in the .bash_aliases file.

By default there is no .bash_aliases file, but you can create one and add some entries to it by typing:

cd ~
gedit .bash_aliases

The first line makes sure you are in your home folder, the second opens the gedit editor and tells it to open a file called .bash_aliases. If no such file exists, it is created. These are some lines from my .bash_aliases file.

alias cls=clear
alias h.=history
alias hf=’history | grep $1′
alias pf=’ps -e | grep $1′

The first alias sets cls to clear the screen. It’s just faster to type cls than it is to type clear. Likewise the second line. It’s fewer keystrokes to hit h. instead of history.

The hf alias is a bit more interesting. I use the history option a lot. hf makes it a bit easier to locate the command you want. For instance, to see the files you have recently opened in gedit, you could type:

hf gedit

The result on my test machine is shown here. The commands that have gedit in them are listed with the gedit highlighted in red.

Output from the hf alias
Output from the hf alias

The pf alias does the same sort of thing, but with process names instead of command names. You can use it to list all of the processes that have a certain word in their name. In the example below I have used the pf alias twice, once to list all the processes that have gnome in their name and once to list all processes that have unity in their name.

Output from the pf alias
Output from the pf alias

Note that when you have typed your aliases into the bash_aliases file, you must save the file, and exit the terminal session, and open a new terminal window before the aliases become available for use.

Remember, because the .bash_aliases file is a dotfile (its name starts with a full stop), the .bash_aliases file will not be listed when you use the ls command.

To see dotfiles you have to use the the -a or -A parameters, or use the la system-provided alias.

Tags : , , ,

2 thoughts on “Putting Aliases in the .bash_aliases File”

  1. Thank you. It’s 2018, five years later, and this is still useful for someone like me. I’m living with Linux Mint 19 Tara right now by the way.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.