$ cat a.sh
#!/bin/bash
echo -n "apple" | shasum -a 256
$ sh -x a.sh
+ echo -n apple
+ shasum -a 256
d9d20ed0e313ce50526de6185500439af174bf56be623f1c5fe74fbb73b60972 -
$ bash -x a.sh
+ echo -n apple
+ shasum -a 256
3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b -
最后一个是正确的。 这是为什么?以及如何解决?
最佳答案
根据 POSIX,echo
不支持任何选项。
因此,当 echo -n
与 sh
一起运行时,它输出 literal -n
而不是解释-n
作为 no-trailing-newline 选项:
$ sh -c 'echo -n "apple"'
-n apple # !! Note the -n at the beginning.
注意:并非所有 sh
实现都是这样;一些,例如在 Ubuntu 上(其中 dash
充当 sh
),do 支持 -n
选项,但是关键是如果您的代码必须在多个平台上运行,您不能依赖。
打印到 stdout 的可移植 POSIX 兼容方式是使用 printf
utility :
printf %s "apple" | shasum -a 256
关于linux - Bash/SH,相同的命令不同的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41176637/