nixers
echo -n does not work as expected - Printable Version
+- nixers (https://nixers.net)
+-- Forum: Operating Systems & Administration (https://nixers.net/Forum-Operating-Systems-Administration)
+--- Forum: OS X (https://nixers.net/Forum-OS-X)
+--- Thread: echo -n does not work as expected (/Thread-echo-n-does-not-work-as-expected)


echo -n does not work as expected - jkl - 17-04-2020

(In zsh:)

Code:
$ echo -n 123
123%
$ sh
$ echo -n 123
-n 123

Why? ... And is there a way to make sh on macOS follow the standard so I can make my scripts portable?


RE: echo -n does not work as expected - seninha - 17-04-2020

Use
Code:
printf 123
instead.

Use printf if you do not want the newline.


RE: echo -n does not work as expected - jkl - 17-04-2020

Ah! Thank you. :)

Still doesn't explain why macOS breaks its own manpage here...


RE: echo -n does not work as expected - seninha - 17-04-2020

Echo should not have options.
Each argument of echo should be echoed, so
Code:
echo -n 123
Should print
Code:
-n 123

Quote:And is there a way to make sh on macOS follow the standard so I can make my scripts portable?
Not having -n is the standard way. So echo -n is working as expected.

Here is the comments on -n from the OpenBSD manpage:
Quote:The flag [-n] conflicts with the behaviour mandated by the X/Open System Interfaces option of the IEEE Std 1003.1-2008 (“POSIX.1”) specification, which says it should be treated as part of string. Additionally, echo does not support any of the backslash character sequences mandated by XSI.

echo also exists as a built-in to csh(1) and ksh(1), though with a different syntax.

Where portability is paramount, use printf(1).



RE: echo -n does not work as expected - z3bra - 20-04-2020

If the manpage on Mac OS does not mention the -n. it could be that /bin/echo would behave properly if you try that. However most (if not all?) shell implement echo as a builtin command. and especially bash which is the default shell on Mac OS iirc. So when you call "echo", you effectively call the bash builtin which features a ton of new flags for the echo command. As phillbush and OpenBSD put it, use printf when portability is an issue (echo is considered broken and deprecated in many places).


RE: echo -n does not work as expected - jkl - 20-04-2020

(20-04-2020, 05:35 AM)z3bra Wrote: If the manpage on Mac OS does not mention the -n

It does, that's why I wondered why macOS's sh does not respect it. However, printf works as announced. :)