If you’re tired of typing out long commands time and time again, it’s about time you try using Bash aliases. Bash aliases essentially let you make a short, memorable command and use it in place of a longer command.
In this article, we’re going over how you can make a Bash alias for those long commands that you hate typing.
Also read: How to compare Strings in Bash?
Creating a Bash alias
Now making Bash aliases is actually a rather simple thing. Here’s the basic syntax.
alias aliasName="command_you_want_to_run"
As you can see, the command starts with the alias command followed by the name or the short command you want to use and then equating it with the command you want to run encapsulated in a string.
For example, to make an alias to list a directory in verbose format, you’d normally have to type ls -la. However, you can make an alias for this command and use that instead.
alias ld="ls -la"
Now if you type ld in the terminal, the output will be same as ls -la.
If you declare a Bash alias in the sudoterminal, it’ll stay in memory for as long as the terminal session is active. Once you close the terminal, the alias will be removed. To make an alias persistent, you’re going to have to declare it in either the ~/.bash_profile or ~/,.bashrc files.
Step 1: You can open either of the files using nano.
sudo nano ~/.bashrc
Step 2: Append the alias statement at the end of the file.
alias ldls ="ls -la"
Step 3: Once you’re done, save and exit the file. Now refresh the file by using the following command.
source ~/.bashrc
Also read: How to exit Bash script?
Making Bash aliases with arguments using Bash functions
We’ve already covered Bash functions in a previous article. The great thing about them is that you can also create Bash aliases using functions and pass arguments. This adds a whole new level of versatility to your aliases.
The basic syntax for doing so is the same as the one used for Bash functions, except for the name of the function becomes your alias.
In the below example, we’ve created a bash alias function which will create a directory with the name passed as an argument and then enter the directory.
mkcd ()
{
mkdir -p -- "$1" && cd -P -- "$1"
}
In the above example, — makes sure you’re not passing an extra argument to the command while && ensures that the cd command runs only if the mkdir command terminates successfully.
Like regular aliases, add this function to your ~/.bashrc file and refresh it before you start using the alias.
Also read: Bash While loop explained