How to create short command for commonly used long commands in Linux?

February 16, 2021 - 3 min read

To create a shortcut or short commands for commonly used long shell commands, we can make use of the alias command in linux. So that whenever the short command is invoked it will originally invoke the long command mapped to it.

You can create an alias for a commonly used command like this,

# Create short commands
# for commonly used commands
alias short_command="commonly_used_long_command"

First, you need to type the alias keyword in the terminal followed by a space and then the custom short command, an equal sign (=), and the command you need to invoke inside the quotes.

For example, let's suppose you have to go to a directory every time located at path /Users/john/projects/work/hello-world-project. So you may need to write something like this in the terminal every time 😟.

# Long command 😟
cd /Users/john/projects/work/hello-world-project

This is hard if you are writing this manually every time.

So, let's use the alias command to make a shortcut for this very long command.

Let's make a short command called project so that whenever we type project into a terminal it should invoke the above long command cd /Users/john/projects/work/hello-world-project.

So to make an alias we have to write like this in the terminal and press Enter,

# Using alias command
alias project="cd /Users/john/projects/work/hello-world-project"

Here we have written the short command after the alias keyword and the long command we need to execute inside the quotes.

But till now we have a temporary command and this short command will be destroyed if you close the current terminal. So to make it a permanent command you have to put the above command into your shell configuration profile file.

It can be

  • ~/.zshrc
  • ~/.bashrc

etc.

You need to find out which shell you are using.

This file will be located in the current user directory. You can use your favorite editor like vim, nano, or even vscode to edit the file.

# Open shell configuration file
vim ~/.zshrc
# OR vim ~/.bashrc

A view of the .zshrc file from the VSCode editor

After locating the file, you need to copy the above code, paste it at the end of the shell configuration file and save the file!

The project command won't work yet if you type in the terminal. You need to kind of reboot the terminal.

You can do that using the source command like this,

# To make the alias command work
# in the current terminal session
source ~/.zshrc
# OR source ~/.bashrc

Now you can use your custom short command anywhere in the terminal and it would invoke that long command.

That's it! 😀

Feel free to share if you found this useful 😃.