Tip to write scripts: Internal vs External commands

There are actually two types of Unix commands, internal and external. This concept may be new to new Unix and Linux users, but knowing this will help you write better scripts.

Here are how internal and external commands are defined:

Internal commands are the built in commands of the shell. Which means that when you execute an internal command, no process will be launched to execute the command. Therefore the speed of executing an internal command will be very high. An example for an internal command is 'cd', when you use 'cd' to change the directory, no process is created, the directory is just simply changed.

Some other examples for internal commands: source, fg, bg ...

External commands are executable scripts in separate files. So when you want to execute an external command, a script will be run. For example, when you want to use 'perl', the file /usr/bin/perl will be executed.

Some other examples for external commands: sed, mv, awk, cat ...

To know whether command is internal or external, you can use the following command:
 type command  

And if the command is internal, the output will say that the command is shell builtin. If the command is external, the output will give you the path to the command. For example:

difference between internal and external unix commands

As a matter of fact, most of us rarely care about internal and external commands because we always have to use both types of command when writing scripts. However, if you know which command is internal or external, you can improve the performance of your scripts, because as said above, the executing speed of an internal command is always faster. Its obviously hard to feel the difference of speed with just a single command but if you have a big script, the less external commands you use, the less bulking your script will become.

Of course, we dont usually get the option to choose an internal over an external command. However, a careful look at our scripting practices, we might find quite a few places where we can avoid external commands.

 For example, in a script that you need to do some math problem. Lets say to add 2 numbers. You can use either:
 n=`expr $i+$j`  

or:
 let n=i+j  

The difference between the two is that 'let' is an internal command and 'expr' is an external one. So executing 'expr' will be slower than 'let'. Thats why its recommended to use 'let' instead of 'expr' in a big script.
linux tips and tricks