Linux shell 內部命令與外部命令有什么區別以及怎么辨別


內部命令實際上是shell程序的一部分,其中包含的是一些比較簡單的linux系統命令,這些命令由shell程序識別並在shell程序內部完成運行,通常在linux系統加載運行時shell就被加載並駐留在系統內存中。內部命令是寫在bashy源碼里面的,其執行速度比外部命令快,因為解析內部命令shell不需要創建子進程。比如:exit,history,cd,echo等。

外部命令是linux系統中的實用程序部分,因為實用程序的功能通常都比較強大,所以其包含的程序量也會很大,在系統加載時並不隨系統一起被加載到內存中,而是在需要時才將其調用內存。通常外部命令的實體並不包含在shell中,但是其命令執行過程是由shell程序控制的。shell程序管理外部命令執行的路徑查找、加載存放,並控制命令的執行。外部命令是在bash之外額外安裝的,通常放在/bin,/usr/bin,/sbin,/usr/sbin......等等。可通過“echo $PATH”命令查看外部命令的存儲路徑,比如:ls、vi等。

內部命令和外部命令最大的區別之處就是性能。內部命令由於構建在shell中而不必創建多余的進程,要比外部命令執行快得多。因此和執行更大的腳本道理一樣,執行包含很多外部命令的腳本會損害腳本的性能。

1.內部命令在系統啟動時就調入內存,是常駐內存的,所以執行效率高。

2.外部命令是系統的軟件功能,用戶需要時才從硬盤中讀入內存。

type可以用來判斷一個命令是否為內置命令


type: usage: type [-afptP] name [name ...]
[root@linuxeye ~]# type type
type is a shell builtin
[root@linuxeye ~]# type -p type
[root@linuxeye ~]# type -t type
builtin
[root@linuxeye ~]# type type
type is a shell builtin
[root@linuxeye ~]# type -t type
builtin
[root@linuxeye ~]# type pwd
pwd is a shell builtin
[root@linuxeye ~]# type whiptail
whiptail is /usr/bin/whiptail
[root@linuxeye ~]# type -t whiptail
file

enable既可以查看內部命令,同時也可以判斷是否為內部命令

[root@linuxeye ~]# enable -a #查看內部命令
[root@linuxeye ~]# enable whiptail #非內部命令
-bash: enable: whiptail: not a shell builtin
[root@linuxeye ~]# enable pwd #是內部命令

內部命令用戶輸入時系統調用的速率快,不是內置命令,系統將會讀取環境變量文件.bash_profile、/etc/profile去找PATH路徑。

然后在提一下命令的調用,有些歷史命令使用過后,會存在在hash表中,當你再次輸入該命令它的調用會是這樣一個過程。

hash——>內置命令——>PATH   命令的調用其實應該是這樣一個過程。

[root@linuxeye ~]# type pwd
pwd is a shell builtin
[root@linuxeye ~]# type cat
cat is /usr/bin/cat
[root@linuxeye ~]# pwd
/root
[root@linuxeye ~]# ls linuxeye*
linuxeye.pem linuxeye.txt
[root@linuxeye ~]# cat linuxeye.txt
linuxeye
[root@linuxeye ~]# hash -l #顯示hash表
builtin hash -p /usr/bin/cat cat
builtin hash -p /usr/bin/ls ls
[root@linuxeye ~]# type cat
cat is hashed (/usr/bin/cat)
[root@linuxeye ~]# hash -r #清除hash表
[root@linuxeye ~]# type cat
cat is /usr/bin/cat

從上面操作可以看出。hash表不存放系統內置命令。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM