Skip to content
Advertisement

Bash/SH, Same command different output?

JavaScript

And the last one is correct. Why is that? and how to solve it?

Advertisement

Answer

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:

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement