从执行机制看本质差异
在Linux/Unix系统中,内置命令(builtin)是直接编译进Shell解释器的功能模块,而外部命令则是独立的可执行文件。以Bash为例,当执行type
命令时可以看到:
# 内置命令示例
$ type cd
cd is a shell builtin
# 外部命令示例
$ type ls
ls is /bin/ls
性能关键差异点
内置命令的执行无需创建新进程,直接由Shell解释器处理:
# 进程创建对比测试
$ time for i in {1..1000}; do cd /tmp; done
real 0m0.008s
$ time for i in {1..1000}; do /bin/cd /tmp; done
real 0m2.147s
典型内置命令分类
- 目录操作:cd, pwd, dirs
- 变量操作:export, readonly, local
- 流程控制:if, for, while
- I/O操作:echo, printf, read
获取完整列表的方法
不同Shell版本的内置命令可能不同,获取当前Shell支持的内置命令:
# Bash获取方法
$ compgen -b
# Zsh获取方法
$ print -l ${(k)builtins}
开发中的选择策略
在编写Shell脚本时,应优先使用内置命令:
# 不推荐写法(产生子进程)
sum=0
for i in {1..100}; do
sum=$(expr $sum + $i)
done
# 推荐写法(使用内置算术)
sum=0
for i in {1..100}; do
((sum+=i))
done