程式扎記: [Linux 文章收集] Internal vs External commands

標籤

2016年5月21日 星期六

[Linux 文章收集] Internal vs External commands

Source From Here 
Preface
UNIX commands are classified into two types:
* Internal Commands - Ex: cdsourcefg
Internal commands are something which is built into the shell. For the shell built in commands, the execution speed is really high. It is because no process needs to be spawned for executing it. For example, when using the "cd" command, no process is created. The current directory simply gets changed on executing it.

* External Commands - Ex: lscat
External commands are not built into the shell. These are executables present in a separate file. When an external command has to be executed, a new process has to be spawned and the command gets executed. For example, when you execute the "cat" command, which usually is at /usr/bin, the executable /usr/bin/cat gets executed.


How to get the list of Internal commands?
You can get only if you are in bash shell. Bash shell has a command called "help" which will list out all the built-in shell commands.


How to find out whether a command is internal or external? 
Using command type:
# type cd
cd is a shell builtin
# type cat
cat is /usr/bin/cat

For the internal commands, the type command will clearly say its shell built-in, however for the external commands, it gives the path of the command from where it is executed.

Internal vs External?
The question whether should we use an internal command or an external command OR which is better always does not make sense. Because in most of the situations you will end up using the command which does your job which could be either internal or external. The big difference in internal vs external command is performance. Internal command are much much faster compared to external for the simple reason that no process needs to be spawned for an internal command since it is all built-into the shell. So, as the size of a script gets bigger, using external commands a lot does adds to its performance.

Not always we get a choice 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, Say to add 2 numbers say x & y:
- Not Good
- Good
let is a shell built-in command, whereas expr is an external command. Using expr will be slower. This might be very negligible when you are using it at an one-off instance. Using it in a place say on every record of a file containing million records does give a different dimension to it.


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!