Linux Shell 執行指令時,會依優先順序搜尋:別名 → 內建指令 → Hash 快取 → PATH 目錄下的外部執行檔。理解此機制對撰寫高效腳本、排除指令衝突、優化啟動速度至關重要。本文系統化說明內建/外部指令差異、判斷工具 type/enable 用法、Hash 表運作與管理。

| 特性 | 內建指令 | 外部指令 |
|---|---|---|
| 儲存位置 | Shell 進程記憶體中 (常駐) | 檔案系統路徑 (如 /usr/bin/) |
| 載入時機 | Shell 啟動時載入 | 首次呼叫時從磁碟讀入記憶體 |
| 執行效率 | 極高 (無 fork/exec 開銷) | 較低 (需 fork 子進程 + exec 載入) |
| 修改環境 | 可直接修改當前 Shell 環境 (如 cd, export) |
在子進程執行,無法影響父 Shell 環境 |
| 典型範例 | cd, pwd, export, alias, type |
ls, cat, grep, vim, docker |
type [-afptP] name [name ...]
# 範例
$ type type
type is a shell builtin
$ type -t type
builtin
$ type -p type
# 無輸出 (非外部指令)
$ type pwd
pwd is a shell builtin
$ type whiptail
whiptail is /usr/bin/whiptail
$ type -t whiptail
file
| 參數 | 說明 |
|---|---|
-t |
輸出單一類型:alias, keyword, function, builtin, file, 空字串 (不存在) |
-p |
若為外部指令,輸出完整路徑;否則無輸出 |
-a |
顯示所有同名指令 (含別名、內建、PATH 中多個路徑) |
-f |
忽略 Shell 函數,僅查找內建/外部 |
-P |
強制搜尋 PATH,即使為內建指令也回傳路徑 (若存在同名外部檔) |
# 列出所有內建指令
enable -a
# 測試指令是否為內建
enable whiptail
# -bash: enable: whiptail: not a shell builtin
enable pwd
# 無輸出 = 成功 (pwd 為內建)
alias)builtin)# 查看目前 Hash 表
$ hash -l
builtin hash -p /usr/bin/cat cat
builtin hash -p /usr/bin/ls ls
# 執行外部指令後,自動加入 Hash
$ cat test.txt
$ type cat
cat is hashed (/usr/bin/cat)
# 清除 Hash 表 (如外部指令移動位置後)
$ hash -r
$ type cat
cat is /usr/bin/cat
注意:Hash 表不儲存內建指令,僅針對外部指令。
date, stat) 可改用內建替代 (如 printf '%(%s)T\\n' -1 替代 date +%s)type -a cmd 可發現同名別名/函數/多路徑外部指令type -t 確認實際執行的是內建、別名還是哪個路徑的外部檔掌握指令分類與搜尋機制,能讓 Shell 操作更精準、腳本更健壯、除錯更高效。
Ubuntu 系統配置 IPv4 網路參數完整教學(DHCP、靜態 IP、虛擬 IP、DNS)
Linux tmpfs 記憶體檔案系統實戰:原理、預設大小、動態佔用與 Oracle AMM/臨時檔案加速應用
Ubuntu 筆電降溫雙重奏:laptop-mode-tools 與 swappiness 優化
Linux 檔案系統核心架構深度解析:物理磁碟結構、Superblock、Inode、Data Block、目錄項、掛載流程
CentOS 透過 yum 安裝 jwhois 套件以支援 whois 域名查詢指令