DEV Community

Alan Constantino
Alan Constantino

Posted on

Creating Aliases on Linux and Mac

If you found this article useful consider donating.

Note: The following steps should also apply to MacOS as well.

Are you tired of typing long commands into the terminal? Did you misremember a flag causing an error making you pull out your hair for 2 minutes only to realize that flag doesn't exist? Well worry no more because I'll be showing you how to create aliases for all of those pesky hard-to-remember commands.

What are aliases?

An alias is just a fancy term for nicknaming a certain command.

They are very useful because instead of typing out a long command with several flags and options, you can nickname it to a shorter command (i.e. give it an alias) and simply remember the shorter command.

Editing the ".bashrc" File

The first step in creating aliases is to open up a new terminal window and head over to your user's directory like so:

cd /home/<username>
Enter fullscreen mode Exit fullscreen mode

Note: By convention, you would usually define your aliases inside of the ".bashrc" file but because defining all of your aliases here can get out of hand pretty quick, we'll be creating a separate file in which we'll be defining our aliases.

From here, you'll want to open up the ".bashrc" file like so:

sudo nano .bashrc
Enter fullscreen mode Exit fullscreen mode

Inside of ".bashrc" you'll want to paste in the following snippet of code:

# Alias
if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi
Enter fullscreen mode Exit fullscreen mode

The snippet of code above simply tells bash that if the file ".bash_aliases" exists then load it and run it.

Now, enter CTRL + X then Y then ENTER to save the file.

Creating Aliases

Inside of the "/home/" directory, you'll want to create a new file called ".bash_aliases." You can do so with the following command:

touch .bash_aliases
Enter fullscreen mode Exit fullscreen mode

It's in this file that you'll want to create your aliases. Open up the ".bash_aliases" file like so:

sudo nano .bash_aliases
Enter fullscreen mode Exit fullscreen mode

Now, to create an alias you can do the following:

# MAKING AN ALIAS
## alias <name of alias>="<bash command>"
##
## Example:
## alias l="ls -lah"
##
## To apply changes run the following:
## source ~/.bashrc

alias l="ls -lah"
Enter fullscreen mode Exit fullscreen mode

To save your file you can do CTRL + X then Y then ENTER.

Now, enter one last command to load our aliases.

source ~/.bashrc
Enter fullscreen mode Exit fullscreen mode

That's it!

Now, if you type in your custom alias into the terminal, it would be like if you were actually typing the longer command that you aliased.

Note: Every time you edit the ".bash_aliases" file you will have to reload the ".bashrc" file or start a new terminal session for the changes to take effect.

Thanks and have a good one!

If you found this article useful consider donating.

Top comments (0)