Linux Shell 指令分為「內建指令」與「外部指令」兩大類,它們的載入方式、執行效率、環境影響截然不同。本文詳細解析兩類指令的特徵、識別方法、PATH 搜尋機制與實戰差異。

fork/exec 開銷cd, pwd, echo, export, unset, alias, unalias,
read, printf, test, [, [[,
break, continue, return, exit,
source, ., type, command, builtin,
jobs, fg, bg, kill, disown,
ulimit, umask, set, shopt,
history, fc, bind, complete,
declare, local, readonly,
exec, eval, trap, shift,
getopts, let, (( )), mapfile
$ type cd
cd is a shell builtin
$ type -t cd
builtin
/bin、/usr/bin、/usr/local/bin 等)fork() 子進程 → exec() 載入執行ls, cp, mv, rm, cat, grep, sed, awk, find,
ps, top, kill, df, du, mount, umount,
tar, gzip, ssh, scp, rsync,
git, docker, python, node, java,
gcc, make, cmake,
systemctl, service, journalctl,
apt, yum, dnf, pacman
$ type ls
ls is hashed (/usr/bin/ls)
$ type -t ls
file
$ which ls
/usr/bin/ls
$ ls -l /usr/bin/ls
-rwxr-xr-x 1 root root 133760 ... /usr/bin/ls
| 特性 | 內建指令 | 外部指令 |
|---|---|---|
| 進程建立 | 無 | fork() + exec() |
| 啟動速度 | 極快(微秒級) | 較慢(毫秒級) |
| 記憶體開銷 | 共享 Shell 記憶體 | 獨立進程空間 |
| 環境影響 | 可修改父 Shell 狀態 | 隔離,不影響父 Shell |
| 環境變數修改 | 直接生效 | 僅影響子進程 |
| 工作目錄變更 | cd 直接生效 | 子進程變更不影響父 Shell |
| I/O 重導向 | Shell 直接處理 | 子進程繼承檔案描述符 |
| 信號處理 | Shell 統一管理 | 子進程獨立處理 |
| 可用性 | 需 Shell 支援 | 跨 Shell/語言通用 |
| 類別 | 說明 | 範例 |
|---|---|---|
| 關鍵字 | Shell 語法結構,非指令 | if, for, while, case, function |
| 別名 | 指令替代字串,展開後再解析 | alias ll='ls -l' |
| 函數 | Shell 內定義的程式碼塊 | myfunc() { ... } |
| 保留字 | 語法保留,不可作變數名 | then, else, do, done |