在 Linux 中,sh
是一个重要的命令行解释器(Shell),以下是详细说明:
sh
的本质sh
(Bourne Shell)是 Unix/Linux 中最基础的命令行解释器,用于执行用户输入的命令或脚本。sh
通常是其他 Shell 的兼容模式(如 dash
或 bash --posix
),遵循 POSIX 标准。sh -c "echo Hello World" # 通过 sh 执行单条命令
sh script.sh # 使用 sh 解释器执行脚本
#!/bin/sh
,表示用 sh
运行。sh
与其他 Shell 的关系Shell 名称 | 特点 | 与 sh 的关系 |
---|---|---|
bash |
功能扩展(支持数组、彩色输出等) | 兼容 sh ,但非纯 POSIX 模式 |
dash |
轻量快速,严格 POSIX 兼容 | 许多系统中 /bin/sh 实际链接到 dash |
zsh |
交互式功能强大(如自动补全) | 不默认兼容 sh ,需配置 |
#!/bin/sh
,应避免使用 bash
特有语法(如 [[ ]]
或 {1..10}
)。bash
ls -l /bin/sh # 常见输出:/bin/sh -> dash(Ubuntu)或 /bin/sh -> bash(CentOS)
dash
(作为 sh
)比 bash
更快,适合系统启动脚本。sh
?sh
与 bash
的区别# 在 sh 中会报错(非 POSIX 语法)
array=(1 2 3)
echo ${array[1]}
# 在 bash 中正常
bash -c 'array=(1 2 3); echo ${array[1]}'
sh
是执行命令和脚本的入口。#!/bin/sh
时需遵守 POSIX 规范。/bin/sh
可能指向不同解释器。如需功能扩展(如条件判断增强),建议显式使用 #!/bin/bash
。