How to use Alias to enter commands faster

Have you repeatedly used Linux commands with flags etc that were tedious to enter? Using CTRL + Arrow Keys only gets you so far. The next step from simply using Linux history to bring up commands is to alias them.

Motivation

One of the tasks of a programmer is to automate repetitive things. Sometimes it adds a little overhead to actually doing the task but after automating it, changing it to the new requirements is usually faster than doing the task again manually. In this article, I shall explain how to automate one such range of tasks.

Quite often one needs to enter a specific Linux command. Few examples from my experience:

  • List all process threads with a particular name
  • Find a file and navigate to that directory
  • Run a script with a bunch of flags

And sure, one can enter them correctly once, and then if required again, one can make use of the bash history. But that takes time too. There should be a way to refer to them with fewer keystrokes. An alias does just that.

Interested? Read ahead.

Using alias

Here's a line from the alias man page:

An alias definition provides a string value that shall replace a command name when it is encountered

In simple terms, we can create small (albeit meaningful) variables for our commands and enter those instead.

To get the current list of aliases stored currently, enter the command alias.

alias

1. Create a new alias

Adding a new alias is as simple as creating a variable in a programming language:

alias test='ps'

ps gives information about active processes. After the command above is entered, we can enter test to get the same output.

image.png

2. Add a script file as an alias

Similarly, one can alias a bash script as a command as well.

alias myscript='bash /path/to/script.sh'

An advantage of using a script file is that one can edit the file but still myscript doesn't need to be changed since it's just executing the script.

Persist alias through terminal sessions

To make your aliases remain after closing terminals, one needs to enter them in your terminal rc files. For example, here are a few lines of my .bashrc file:

image.png

Similarly, to add new aliases, simply type them in your .rc file and use the source command to bring up them in the same terminal session.

Summary

Use alias to envoke repetitive and long commands with shorter words. Add them to the terminal rc file to make them permanent.