Creating New Commands in Linux

We can create our own shell commands. These commands are actually derived from shell’s own command. We can create a new command with our own name in replacement of a frequently used pipeline.

Let us take the pipeline example ‘who | wc -l’. Let the new name be ‘my’. The first step is to create an ordinary file ‘my’ with its content as ‘who | wc -l’.

To run our command type

sh my

But every time when we execute these commands we need to type sh before our command. To avoid this, we have to the file executable. These type of executable files are called shell file.

chmod +x my

makes the file executable. Now to execute the command we have to type ‘my’ only.

But this works only if the file is in our current directory and the current directory is in the shell variable PATH. The path can be listed using

echo $PATH

If the command my is not in the current directory, we have to move the file ‘my’ to current directory.

It is also possible to create command which takes arguments or parameters.

eg: chmod +x filename

To create such a command, say xm, we have to create a file xm with content ‘chmod +x $1’. $1 is to take the first argument. To take more than one argument, we can use $2, $3, … $9. But if more than 9 arguments are there, we cannot use $10, because it is interpreted as $1 and literal 0. The solution is to use $* in the file

i.e. chmod +x $*

which works regardless of how many arguments are provided with the command. After creation of such a file, the steps are as normal creation of commands.

Advertisements

About Odol Shinu

I've completed my B Tech in Information Technology in 2010 from Government Engineering College Sreekrishnapuram Palakkad under Calicut University.

Posted on August 17, 2010, in GNU/Linux. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: