0

我试图理解为什么脚本可以使用#!/bin/bash但不能使用#!/bin/sh。我正在运行 Cygwin,两者sh.exe似乎bash.exe都相同(文件大小相同)。

$ cat 1.sh
#!/bin/sh
while read line; do
  echo ${line:0:9}
done < <(help | head -5)

$ ./1.sh
./1.sh: line 4: syntax error near unexpected token `<'
./1.sh: line 4: `done < <(help | head -5)'

$ cat 2.sh
#!/bin/bash
while read line; do
  echo ${line:0:9}
done < <(help | head -5)

$ ./2.sh
GNU bash,
These she
Type `hel
Use `info
Use `man
4

2 回答 2

5

尽管是同一个文件,shell 在运行时会分析自己的名称并切换到普通 shell 或 bash 模式。

于 2012-06-16T07:55:25.207 回答
2

问题

  1. Bash 是 Bourne shell 的超集,在 Bash 中可以实现的许多事情在更有限的 shell 中是不可能的。
  2. 即使sh是到bash的硬链接,它在作为sh调用时的行为也会有所不同。Bash shell 支持的许多功能在此模式下将不起作用。

解决方案

  1. 从脚本中删除你的bashisms,包括漂亮的特性,比如你在第 4 行的进程替换。
  2. 以 Bash 的身份运行您的脚本,而不是普通的 Bourne。
于 2012-06-16T08:03:13.443 回答