Bash / SH, The same team result?

$ 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 true. Why is this? and how to solve it?

+8
linux bash shell sh
source share
1 answer

On POSIX, echo does not support any parameters.

Therefore, when echo -n starts with sh , it outputs the literal -n instead of interpreting -n as the no-trailing-newline option:

 $ sh -c 'echo -n "apple"' -n apple # !! Note the -n at the beginning. 

Note. Not all sh implementations behave this way; some, for example, on Ubuntu (where dash acts like sh ), support the -n option, but the fact is that you cannot rely on this if your code should work on multiple platforms.

A portable POSIX-compatible way to print to stdout is to use the printf utility :

 printf %s "apple" | shasum -a 256 
+12
source share

All Articles