bash - perl shasum 与 bash shasum

标签 bash perl sha

以下 bash 和 Perl 脚本神秘地给出了不同的结果。为什么?

#!/bin/bash                                                                       
hash=`echo -n 'abcd' | /usr/bin/shasum -a 256`;
echo $hash;

#!/usr/bin/perl                                                                   
$hash = `echo -n 'abcd' | /usr/bin/shasum -a 256`;
print "$hash";

bash 脚本:

$ ./tst.sh
88d4266fd4e6338d13b845fcf289579d209c897823b9217da3e161936f031589 -

Perl 脚本:

$ ./tst.pl
61799467ee1ab1f607764ab36c061f09cfac2f9c554e13f4c7442e66cbab9403  -

怎么了?

最佳答案

总结:在您的 Perl 脚本中,-n 被视为包含在 echo 输出中的参数,而不是用于抑制换行的标志。 ( 尝试

$hash = `echo -n 'abcd'`;

确认)。请改用 printf


Perl 使用/bin/sh 在后台执行代码。即使 /bin/sh 是指向 bash 的链接,当通过类似的方式调用时,它的行为也会有所不同。在 POSIX 模式下,

echo -n 'abcd'

会输出

-n abcd

也就是说,-n 选项不被识别为禁止换行的标志,而是被视为要打印的常规参数。在每个脚本中将 echo -n 替换为 printf,您应该从每个脚本中获得相同的 SHA 哈希值。

(更新:bash 3.2,当作为 sh 调用时,显示此行为。较新版本的 bash 似乎继续处理 -n 作为 sh 调用时的标志。)


更好的是,不要花钱去做你可以用 Perl 做的事情。

use Digest::SHA;

$hash = Digest::SHA::sha256('abcd');

出于好奇,这里是 POSIX 规范 has to say关于 echo。我不确定如何理解 XSI 一致性; bash echo 需要 -e 选项来特殊处理转义字符,但几乎每个 shell —除了旧版本bash,然后仅在特殊情况下——将 -n 视为标志,而不是字符串。好吧。

The following operands shall be supported:

string
A string to be written to standard output. If the first operand is -n, or
if any of the operands contain a <backslash> character, the results are
implementation-defined.

On XSI-conformant systems, if the first operand is -n, it shall be treated
as a string, not an option. The following character sequences shall be
recognized on XSI-conformant systems within any of the arguments:

\a
Write an <alert>.
\b
Write a <backspace>.
\c
Suppress the <newline> that otherwise follows the final argument in the output. All characters following the '\c' in the arguments shall be ignored.
\f
Write a <form-feed>.
\n
Write a <newline>.
\r
Write a <carriage-return>.
\t
Write a <tab>.
\v
Write a <vertical-tab>.
\\
Write a <backslash> character.
\0num
Write an 8-bit value that is the zero, one, two, or three-digit octal number num.

关于bash - perl shasum 与 bash shasum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26067811/

相关文章:

用于从 ubuntu 安装特定软件包的 Bash 脚本(如果存在)

linux - 从标准输出中获取输出的最后 4 个字符

perl - 从复杂的数据库提取 (SQL) 构建树状哈希 (YAML)?

perl - 如何在 unix 环境中的任何地方运行 perl 脚本?

java - 在 Java/Android 中使用多个值生成 SHA 256 哈希

java - Go SHA-256 哈希不同于 Java SHA-256 哈希

git - 带有 virtualenv 和 git 分支的 Bash 命令提示符

java - 从 Java 执行 Shell 脚本,具有读取操作的 Shell 脚本

perl - 您认为 2010 年 Perl 的哪些新功能最有用?

ssl-certificate - Azure云服务可以使用sha256证书吗