Aliases are simplified names you give a command used regularly. Aliases are also useful to remember commands and learn basic shell scripting.
Creating an Alias text file is a good way to maintain aliases. This file can be named '.alias' and placed in your home directory. This alias file should then be imported to your user PATH so you may call your aliases when needed.
Create an Alias File
Go to your home directory and create a textfile named ‘.alias’.
touch .alias
Creating Aliases
Open this text file in a text editor like vim or nano, and write a custom command following this pattern.
alias la='ls -a'
The first ‘alias’ keyword tells the system this is an alias you which to set. The ‘la’ word is the name of the alias command you which to create. Following this name, you then place an ‘equal’ sign and then, within single or double quotes, write the command you which to execute when calling the custom name. In this case, ‘ls -a‘ runs the ls command with the ‘a‘ flag which makes the output of ls show all files within that directory, even hidden ones.
Source Aliases on your Shell Configuration
Once you create an alias file, you must source it from your shell configuration. Then the aliases can be called and executed.
In Bash, this is done on your ‘.zshrc’ or ‘.bashrc’ files by first testing if the file exists, and then if it exist, source it.
if [ -f $HOME/.alias ]; then
source ~/.alias
fi
This block of code first tests if the alias file exists, then it proceeds to source it and adds all these aliases to your environment.
See an Alias Command
Once you create many aliases, you can also query the shell for the actual command that is called when executing an alias name. Seeing what command corresponds to an alias is useful to know exactly what will be run when calling it. It will also help you remember custom commands you use.
To see the command that corresponds to an alias name, write the word alias followed by the alias name you wish to see the command.
alias la
This will return the command executed when running the ‘la‘ alias, which is ‘ls -a‘.
See List of All Aliases
alias
Executing the command alias by itself shows a list of all aliases which are part of your environment.
Useful Aliases
These are aliases I recommend maintaining in an alias file. These will help you manage all other aliases you write.
Source Alias File After Editing
alias sourcealiases='source ~/.alias'
Sort Aliases File After Editing
alias sortaliases='sort -o ~/.alias ~/.alias'
Edit Alias File
alias editalias='vim ~/.alias'
These three aliases help you create, import and organize aliases as you work.
Conclusion
Shell aliases are a great way to name and remember custom commands you use daily within your Unix-like environment. You also may share this aliases with friends and even publish them publicly for others to build and learn with them.