How to create custom bash commands?
Ever since we have used computer, all might have heard of command line tool. Most commonly called bash. Command line is capable of taking input and outputting its results from and to computer. One of the features command line offers is it lets the users to create their own instructions. In this article we will take a tour through the steps on creating our own bash command.
Create custom command on Bash
This feature comes hand full when we are executing 2 or 3 everyday commands to do a single functionality. Let me make the picture more clear. I don't know how many would have created a virtual host. Here I'm considering the virtual host as the scenario. On creating virtual host, include the ip address along with the host name in /etc/hosts/ file. So let's get started.
[Hint: Assuming you are using Linux OS]
For performing with task one must execute the following tasks,
- Go to /etc folder using
cd /etc folder.
- Now open the hosts file to edit by sudo nano hosts.
So, why we do this all the time, when ever we want to add a newly created host to hosts file.
I have created a custom command for doing this by executing a single command. The steps to create these commands would be a mess, but I bet this is something very useful.
Lets start creating our own command,
- Open up the terminal, type the command
Now a plain space must appear in your terminal.
- Now enter the following
#!/bin/bash #command to open /etc/hosts file sudo nano /etc/hosts
Let me explain, The symbol you see is often referred as 'HashBang' which points to /bin/bash which means the command we've entered in this case sudo nano /etc/hosts runs using bash program. Second line is the comment for the instruction for later reference. Third line refers to the set of instructions to execute. .
- Save the file with the name of your costum command you intend to make. Lets name it as 'ghost' in short of go to hosts file.
- Now If you try to execute the command we have created, let's say ghost, you can notice that the 'command not found'.
- As a next step, move the file to /usr/bin
cp -i ghost /usr/bin
Here we are copying ghost to /usr/bin folder
- Now try to type ghost on bash, you we see 'permission denied' error.
- From above we must get a clue, that the file we created is not executable. So lets move to give the file executing permission
chmod +x ghost
- Now make a run to execute your command on terminal. It must open up the hosts file in etc folder.
Bash is providing a universe of pre defined commands. Lets make it our own by putting some effort in customizing. By this way, we can create our own commands for everyday combination of commands we use in one step. Bash can do tasks faster than Graphical Interface. It also allow access to more commands and scripts.