9
$ 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 correct. Why is that? and how to solve it?

2
  • For reference, I get the last one if I try csh or zsh also. But I get the same result for all 4 if I omit -n from echo. Commented Dec 16, 2016 at 3:06
  • 1
    Moral of the story: if the output of the command differs, rethink your assumptions about its input. Commented Dec 17, 2016 at 15:37

1 Answer 1

13

Per POSIX, echo supports no options.

Therefore, when echo -n is run with sh, it outputs 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, such as on Ubuntu (where dash acts as sh), do support the -n option, but the point is that you cannot rely on that, if your code must run on multiple platforms.

The portable POSIX-compliant way to print to stdout is to use the printf utility:

printf %s "apple" | shasum -a 256
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.