bash vs sh

一般来讲,/bin/sh 都是软连接到bash的,所以,你基本上会认为 /bin/sh 和 /bin/bash 是一样的; 但事实是:不尽然

bash中有判断当前文件名的逻辑,如果是sh 就 xxx, 如果是bash 就 ***,如:

使用bash执行脚本时,函数名允许含有中划线(如: hello-world),sh执行时不允许; 注意,使用中划线定义的函数,如果要unset时,则需要使用-f选项,如: unset -f “hello-world” ; 因为如果没有-f选项,unset会尝试unset对应的变量,但是这是个不合法的变量,所以,直接退出, -f选项直接unset对应的函数

使用bash执行脚本时,支持Process Substitution , sh 执行时不支持

 

是不是感觉有些不爽?

还有呢,有些版本的 /bin/test 和 /bin/[ 就是同一个程序,根据文件名的不同执行不同的逻辑

 

参考: https://stackoverflow.com/questions/5725296/difference-between-sh-and-bash

当通过sh的方式使用bash时,基本等同于:

虽然显得很posix,但是很多好用的东西不支持:(其中删除线部分,似乎说的不太对,也或者是我理解的不对,所以删除了)

This question has frequently been nominated as a canonical for people who try to use sh and are surprised that it’s not behaving the same as bash. Here’s a quick rundown of common misunderstandings and pitfalls.

  • If you run your script with sh scriptname, or run it with scriptname and have #!/bin/shin the shebang line, you should expect POSIX sh behavior.
  • If you run your script with bash scriptname, or run it with scriptname and have #!/bin/bash (or the local equivalent) in the shebang line, you should expect Bash behavior.

Having a correct shebang and running the script by typing just the script name (possibly with a relative or full path) is generally the preferred solution. In addition to a correct shebang, this requires the script file to have execute permission (chmod a+x scriptname).

The Bash Reference manual has a section which attempts to enumerate the differences but some common sources of confusion include

  • [[ is not available in sh (only [ which is more clunky and limited). 
  • sh does not have arrays.
  • Bash has process substitution with <(cmd) and >(cmd).
  • Some Bash keywords like local, function, and select are not portable to sh.
  • ~ refers to $HOME only in Bash (and more generally ~username to the home directory of username).
  • Bash has many C-style syntax extensions like $'string\nwith\tC\aescapes' and the three-argument for((i=0;i<=3;i++)) loop, += increment assignment, etc.
  • Bash has *.{png,jpg} and {0..9} brace expansion.
  • Bash supports coprocesses with <> redirection.
  • Bash supports <<<'here strings'.
  • Bash has significantly extended facilities for shell arithmetic (though still no floating-point support) and variable substring manipulation.
  • Many, many Bash-only extensions to enable or disable optional behavior and expose internal state of the shell.

Remember, this is an abridged listing. Refer to the reference manual for the full scoop, and http://mywiki.wooledge.org/Bashism for many good workarounds; and/or try http://shellcheck.net/ which warns for many Bash-only features.

Unfortunately, Bash will not warn when you try to use these constructs when it is invoked as sh.

 

总结:

知道bash和sh有差异就行了,记住所有的差异没有意义

留下评论

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据