[英]Bash/SH, Same command different output?
$ 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
), 確實支持-n
選項,但重點是如果你的代碼必須在多個平台上運行,你就不能依賴它。
符合POSIX標准的便攜式打印到stdout的方法是使用printf
實用程序 :
printf %s "apple" | shasum -a 256
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.