$ 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 -
And the last one is correct. Why is that? and how to solve it?
最后一个是正确的。这是为什么?以及如何解决?
1 个解决方案
#1
12
Per POSIX, echo
supports no options.
根据POSIX,echo不支持任何选项。
Therefore, when echo -n
is run with sh
, it outputs literal -n
instead of interpreting -n
as the no-trailing-newline option:
因此,当echo -n与sh一起运行时,它输出literal -n而不是解释-n作为no-trailing-newline选项:
$ sh -c 'echo -n "apple"'
-n apple # !! Note the -n at the beginning.
Note: Not all sh
implementations behave this way; some, such as on Ubuntu (where dash
acts as sh
), do support the -n
option, but the point is that you cannot rely on that, if your code must run on multiple platforms.
注意:并非所有sh实现都以这种方式运行;一些,比如Ubuntu(其中dash用作sh),确实支持-n选项,但重点是如果你的代码必须在多个平台上运行,你就不能依赖它。
The portable POSIX-compliant way to print to stdout is to use the printf
utility:
符合POSIX标准的便携式打印到stdout的方法是使用printf实用程序:
printf %s "apple" | shasum -a 256
#1
12
Per POSIX, echo
supports no options.
根据POSIX,echo不支持任何选项。
Therefore, when echo -n
is run with sh
, it outputs literal -n
instead of interpreting -n
as the no-trailing-newline option:
因此,当echo -n与sh一起运行时,它输出literal -n而不是解释-n作为no-trailing-newline选项:
$ sh -c 'echo -n "apple"'
-n apple # !! Note the -n at the beginning.
Note: Not all sh
implementations behave this way; some, such as on Ubuntu (where dash
acts as sh
), do support the -n
option, but the point is that you cannot rely on that, if your code must run on multiple platforms.
注意:并非所有sh实现都以这种方式运行;一些,比如Ubuntu(其中dash用作sh),确实支持-n选项,但重点是如果你的代码必须在多个平台上运行,你就不能依赖它。
The portable POSIX-compliant way to print to stdout is to use the printf
utility:
符合POSIX标准的便携式打印到stdout的方法是使用printf实用程序:
printf %s "apple" | shasum -a 256