linux - Bash/SH,相同的命令不同的输出?

标签 linux bash shell sh

$ 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 -nsh 一起运行时,它输出 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/

相关文章:

linux下c++编译错误

linux - 如何使用输入选项 I 在 Linux 中强制安装应用程序?

bash - 我怎样才能更频繁地更新 bash_history?

linux - 我在创建 sed 脚本时遇到问题

linux - 无法找到软件包 oracle-java8-installer linux mint

java - Tomcat 领域形式 : login always fails

linux - Bash 中的管道 : One at a Time (Line by Line) or All at Once

linux - 在linux shell中获取所有别名

linux - shell脚本终止程序但不终止脚本本身

bash - 从shell脚本中的行首删除字符?