/bin/sh 与 /bin/bash 的区别

时间:2021-03-20 09:08:05

今天学习 Linux 的时候遇到一个问题。

#!/bin/sh
# test.sh

USERNAME='hcbbt'
echo "My name is ${USERNAME}. You call me ${USERNAME:0:1}-chan."

这个脚本直接运行时报错了:./test.sh: 5: ./test.sh: Bad substitution
折腾了下,发现第一行的解释器改成 /bin/bash 就没问题了。

于是顺手查了下 /bin/sh/bin/bash 的区别,用 : 截取字符串不是POSIX 标准的。

区别

  1. sh 一般设成 bash 的软链 (symlink)
    ls -l /bin/shlrwxrwxrwx 1 root root 4 Sep 14 04:45 /bin/sh -> dash

  2. 在一般的 linux 系统当中(例外如 FreeBSD,OpenBSD 等),使用 sh 调用执行脚本相当于打开了bashPOSIX 标准模式
  3. 也就是说 /bin/sh 相当于 /bin/bash --posix

所以,它们之间的各种差异都是来自 POSIX 标准模式bash 的差异,比如 用 : 截取字符串,不能用 let , 遇错中断 等等,在使用时需要注意。

参考

  1. [Difference between sh and bash] http://*.com/questions/5725296/difference-between-sh-and-bash
  2. [/bin/bash和/bin/sh的区别] http://www.cppblog.com/erran/archive/2012/05/24/176038.aspx
  3. [#!/bin/sh與#!/bin/bash的區別] http://fanli7.net/a/bianchengyuyan/_NET/20130916/424894.html