How To Create Bash Alliases.
This article explains how to create bash aliases so you can be more productive on the command line.
Creating Bash Aliases
Creating aliases in bash is very straight forward. The syntax is as follows:
An alias declaration starts with the alias keyword followed by the alias name, an equal sign and the command you want to run when you type the alias.
The ls command is probably one of the most used commands on the Linux command line.
Now, if you type ll in your terminal, you’ll get the same output as you would by typing ls -la.
The ll alias will be available only in the current shell session. If you exit the session or open a new session from another terminal, the alias will not be available.
To make the alias persistent you need to declare it in the ~/.bash_profile or ~/.bashrc file.
Open the file in your text editor :
and add your aliases:
The aliases should be named in a way that is easy to remember. It is also recommended to add a comment for future reference.
Once done, save and close the file. Make the aliases available in your current session by typing:
As you can see, creating simple bash aliases is quick and very easy.
Creating Bash Aliases with Arguments (Bash Functions)
Sometimes you may need to create an alias that accepts one or more arguments. That’s where bash functions come in handy.
The syntax for creating a bash function is very easy. They can be declared in two different formats:
To pass any number of arguments to the bash function simply, put them right after the function’s name, separated by a space. The passed parameters are $1, $2, $3, etc., corresponding to the position of the parameter after the function’s name. The $0 variable is reserved for the function name.
Let’s create a simple bash function which will create a directory and then navigate into it:
Same as with aliases, add the function to your ~/.bashrc file and run source ~/.bash_profile to reload the file.
Now instead of using mkdir to create a new directory and then cd to move into that directory , you can simply type:
If you wonder what are — and && here is a short explanation.
— – makes sure you’re not accidentally passing an extra argument to the command. For example, if you try to create a directory that starts with – (dash) without using — the directory name will be interpreted as a command argument.
&& – ensures that the second command runs only if the first command is successful.
By now you should have a good understanding of how to create bash aliases and functions that will make your life on the command line easier and more productive.