bash - 为什么 read 在 bash 和 dash 中的行为不同?

标签 bash shell dash-shell built-in

这是试图找出读取实用程序如何在多个 shell 中工作的尝试。发现了一个对我来说似乎是错误的差异。

结果是破折号保留了尾随空格:

dash: <a b     >
bash: <a b>

简而言之:为什么这段代码在 bash 和 dash read 中的表现不同?

dash -c 'echo "    a b     " | { read var; echo "<$var>"; }'
bash -c 'echo "    a b     " | { read var; echo "<$var>"; }'

最佳答案

这里有一种更简单的方式来展示您的问题:

$ dash -c 'echo "a b     " | { read var; echo "<$var>"; }'
<a b     >
$ bash -c 'echo "a b     " | { read var; echo "<$var>"; }'
<a b>

只有当有两个或多个字段时才会发生这种情况,例如 "a b ",而不是只有一个字段时,例如 "a "

这是 what POSIX says (强调我的):

If there are fewer vars than fields, the last var shall be set to a value comprising the following elements:

  • The field that corresponds to the last var in the normal assignment sequence described above

  • The delimiter(s) that follow the field corresponding to the last var

  • The remaining fields and their delimiters, with trailing IFS white space ignored

dash 不会忽略结尾的 IFS 空格,因此它似乎违反了 POSIX。

bash 行为是正确的。

关于bash - 为什么 read 在 bash 和 dash 中的行为不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31887984/

相关文章:

bash - 当我设置-e时如何忽略不同于0的返回值?

linux - 如何通过比较文件名和文件夹名将文件复制到同名文件夹?

shell - 为什么以不同方式运行脚本时需要许可?

ssh - 在 posix 兼容的 shell 上转义 ssh 中传递的参数的最有效方法是什么?

bash - 用破折号检查字符串的子字符串

linux - BASH getopts 具有相同选项的多个脚本

Bash - while 循环的输入

arrays - 如何使用输入数组重复字符串

python - 使用Makefile bash保存python文件的内容