当谈到 shell 脚本时,两个著名的 shell 经常脱颖而出:Bourne Shell (SH) 和 Bourne Again Shell (Bash)。两者都是基于 Unix 和 Linux 的系统的组成部分,提供与操作系统交互的接口。本文旨在深入研究这两种 shell 之间复杂的差异,揭示它们的独特特性,并提供比较分析,以帮助您了解何时以及为何使用其中一种。
SH 和 Bash 是什么?
SH, 原本的伯恩壳牌,于 20 世纪 70 年代推出,作为 Unix 的主要 shell。贝尔实验室的斯蒂芬·伯恩开发了它,因此得名。 SH 以其简单性和便携性而闻名。创建可以在各种 Unix 衍生版本上执行的脚本时,它是一个可靠的选择。
Bash,另一方面,代表谍影重重 SHell。它是原始 SH 的改进版本,由 Brian Fox 为 GNU 项目开发,作为 Bourne Shell 的免费软件替代品。 Bash 是许多 Linux 发行版和 macOS 的默认 shell。它包含来自其他 shell(例如 KornShell (ksh) 和 C shell (csh))的功能,提供更强大的功能和脚本编写功能。
SH 和 Bash 之间的主要区别
-
Syntax Differences: Bash provides more shorthand and enhanced scripting syntax compared to SH. For example, in bash, you can use the double square bracket syntax [[ ]] for tests, which is more robust and safer than the single bracket syntax [ ] used in SH.
|
# SH 语法
if [ $a -lt $b ]; then
echo “$a 小于 $b”
fi
# Bash 语法
if [[ $a -lt $b ]]; then
echo “$a 小于 $b”
fi
|
-
Array Variables: Bash supports array variables, whereas SH does not. Arrays can be useful when you need to work with multiple values stored under a single variable name.
|
# Bash 语法
array=("apple" "banana" "cherry")
echo ${array[1]} # 输出“香蕉”
|
-
命令行编辑:Bash 支持命令行编辑,而这在 SH 中不是标准的。在 Bash 中,您可以使用箭头键导航命令历史记录,使用退格键删除文本,以及使用制表符完成来完成文件名和命令名称。
-
外壳选项:与 SH 相比,Bash 具有额外的 shell 选项。例如,Bash 中的 shopt 命令提供了更改 SH 中不可用的其他 shell 可选行为的能力。
-
Process Substitution: Bash supports process substitution (<(command) and >(command)), allowing a process’s input or output to be referred to using a filename. This feature is not available in SH.
|
# Bash 语法
diff <(command1) <(command2)
|
-
未找到命令挂钩:Bash 有一个特殊的 shell 函数 command_not_found_handle,当未找到命令时执行该函数。 SH 中不提供此功能。
-
Here Strings: Bash supports “Here Strings” which is a form of I/O redirection allowing a string to be used as the input for a command, denoted by <<<. This feature is not available in SH.
|
# Bash 语法
wc -l <<< “这是一个字符串”
|
选择哪个:SH 还是 Bash?
SH 和 Bash 之间的决定归结为您的特定项目的需求。如果您正在创建需要在各种 Unix 系统上运行的脚本,由于其可移植性和兼容性,SH 可能是更好的选择。但是,如果您在 Linux 或 macOS 系统上工作并且需要额外的功能和语法增强,那么 Bash 是首选 shell。
结论
总而言之,SH 和 Bash 都有各自的优势。 SH 是一个经典、简约的 shell,可以完成工作,而 Bash 则为复杂的脚本需求提供了功能更丰富的环境。了解两者之间的差异是成为熟练的 shell 脚本编写者的关键一步。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)