Creating Command Line Aliases
3 June, 2019
If you’re doing any work at the command line, that work probably involves more than a couple of keystrokes. You can save time and reduce the amount you type at the command line in two ways.
One way is to create a script that encapsulates all of the commands and options that you’ll be using to perform an operation. All you need to do is run the script along with, say, a file name. That’s great for single or multiple commands that require a lot of options.
For other commands, an easier way is to create an alias. An alias replaces the command and its options with something shorter. For example, if you want to list the contents of a directory in detail, you can type ls -l at the command line. Or, you can create the alias ll and use that instead.
Let’s take a quick look at how to do that.
It’s All in a File
I’m assuming you’re using the bash shell. If you aren’t, what I’m about to describe should work with your preferred shell.
Crack open a terminal window. Make sure you’re in your home directory – for example, /home/scott. Then, open the file .bashrc in your favourite text editor.
The file .bashrc determines the behaviour of your shell. On some systems, you can also create aliases in the files .bash_profile and .profile. Note that the dot before the name of the file indicates that it’s hidden — you can’t see it when you view the contents of your /home folder in a file manager or at the command line.
Scroll through the file. If you’re lucky, the file might have some sample alias definitions. You can add your aliases after that section. If not, add them at the end of the file.
Creating the Alias
Create an alias by adding this to the file:
alias [command]=‘alias’
For example, if you want to list the contents of a directory and their attributes, create this alias:
alias la=‘ls -a’
Whenever you type la, your shell knows that you mean ls -a.
That’s a pretty example. Useful, but simple. I have others, which you can get a peek at below:
This alias, for example, uses a utility called Ghostscript to merge PDF files:
alias pdfmerge=‘gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=./output.pdf’
All I need to do type pdfmerge and some file names, rather than try to remember that string of commands.
You can do a lot more with aliases, but that’s all I’m going to cover for now.