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
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
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.