Why does bash behave differently, when it is called as sh?

不打扰是莪最后的温柔 提交于 2019-12-01 12:29:49

问题


I have an ubuntu machine with default shell set to bash and both ways to the binary in $PATH:

$ which bash
/bin/bash
$ which sh
/bin/sh
$ ll /bin/sh
lrwxrwxrwx 1 root root 4 Mar  6  2013 /bin/sh -> bash*

But when I try to call a script that uses the inline file descriptor (that only bash can handle, but not sh) both calls behave differently:

$ . ./inline-pipe
reached
$ bash ./inline-pipe
reached
$ sh ./inline-pipe
./inline-pipe: line 6: syntax error near unexpected token `<'
./inline-pipe: line 6: `done < <(echo "reached")'

The example-script I am referring to looks like that

#!/bin/sh
while read line; do
if [[ "$line" == "reached" ]]; then echo "reached"; fi
done < <(echo "reached")

the real one is a little bit longer:

#!/bin/sh
declare -A elements
while read line
do
    for ele in $(echo $line | grep -o "[a-z]*:[^ ]*")
    do
        id=$(echo $ele | cut -d ":" -f 1)
        elements["$id"]=$(echo $ele | cut -d ":" -f 2)
    done
done < <(adb devices -l)
echo ${elements[*]}

回答1:


When bash is invoked as sh, it (mostly) restricts itself to features found in the POSIX standard. Process substitution is not one of those features, hence the error.




回答2:


Theoretically, it is a feature of bash: if you call as "sh", it by default switches off all of its features. And the root shell is by default "/bin/sh".

Its primary goal is the security. Secondary is the produce some level of compatibility between some shells of the system, because it enables the system scripts to run in alternate (faster? more secure?) environment.

This is the theory.

Practically goes this so, that there are always people in a development team, who want to reduce and eliminate everything with various arguments (security, simplicity, safety, stability - but these arguments are going somehow always to the direction of the removal, deletion, destroying).

This is because the bash in debian doesn't have network sockets, this is because debian wasn't able in 20 years to normally integrate the best compressors (bz2, xz) - and this is because the root shell is by default so primitive, as of the PDP11 of the eighties.




回答3:


I believe sh on ubuntu is actually dash which is smaller than bash with fewer features.



来源:https://stackoverflow.com/questions/20195377/why-does-bash-behave-differently-when-it-is-called-as-sh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!