bash 与 sh 脚本不同的结果

bash vs sh script different results

当我在 macOS 的终端中 运行 这些行时,我得到了正确的结果

hex=$(echo -n 'betty' | xxd -p)
echo $hex

6265747479

但是当我在 bash 脚本中 运行 它们时,我得到了完全不同的东西

sh myscript.sh

62657474790a

这就像它出于某种原因在末尾放了一个马车return。为什么?

尝试 bash 而不是 sh。由于 echo 是一个 内置的 命令,它取决于 shell 它是如何执行的。对我来说,来自 sh 的回声似乎不支持 -n:

sh-3.2$ echo -n hello
-n hello
sh-3.2$ echo $(echo -n 'betty' | xxd -p)
2d6e2062657474790a

不同版本的 echo 在给定 -n 作为第一个参数时会做不同的事情。有些人将其打印为输出的一部分,有些人将其解释为一个标志,谁知道会发生什么。根据POSIX standard for echo、"If the first operand is -n, or if any of the operands contain a backslash character, the results are implementation-defined."

最可靠的打印字符串的方法是 printf。它稍微复杂一些,因为你必须给它一个格式字符串以及你想要打印的字符串:

hex=$(printf "%s" 'betty' | xxd -p)