How to create custom commands in Unix/Linux



Few days ago one of my friend told me that the work on linux is so difficult, because he didn’t remember the complex commands of linux and every time when he want to do some debugging on their linux server he always need to google some commands first, so I’ve decided to write this post “How to create custom commands in Unix/Linux”.

There are many ways to do this, I’ve explained some of the easiest way to create custom commands.

  • using a bash/shell script
  • using alias command

Using a bash/shell script

A bash/shell script is a linux program that can be run by a UNIX shell. You can learn more about shell script on wikipedia. we are not here to learn about shell script. I assume you already have a basic knowledge of writing shell scripts.

So, we can learn creating custom command using a simple example.

Suppose you want to create a custom command for printing system’s date and time.

create a file called dt.sh anywhere on your machine using any text editor, i.e. /home/girishgaurav/dt.sh or just name the script what you want to type in to the terminal.


give it the execute permission using

chmod 777 /home/girishgaurav/dt.sh

you done half way, and its really that easy 🙂

now you have two choices to configure this script to be used as a command:

  1. move this script to /usr/bin directory and you just done everything and your custom command named dt is ready to use. just type dt on the shell and see the output.

$ dt

Fri Dec 5 22:49:05 IST 2014

  1. for advance user who don’t want to mix system’s command with your own, you can create a separate directory for your custom commands:
    create a directory called commands in your home directory, i.e. /home/girishgaurav/commands/ or whatever you like and update your path variable to include this commands directory.

now just move the dt.sh to the above created directory and your custom command is ready 🙂

 

Using alias command

The alias command is very useful to create your custom commands. The format is alias name=’command’

Now if you want to do our previous datetime example using alisas, it is more simple than writing a bash script.


and you are done, your custom command is created, is that so easy 🙂

No! it’s not that easy. You’ve created your custom command for the current shell lifetime, and whenever you exit from the shell your command will no longer available for the next time.

So, for permanent, you need to do some more…

create a file called .bash_aliases in your home directory using any text editor or using touch command, i.e. touch ~/.bash_aliases

Now you all done with your custom commands and you can create any command that you want.

Here are some useful aliases that can be helpful for any linux user.

References:

Bash/Shell Script

Alias Command

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: