这是试图找出读取实用程序如何在多个 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/