echo -n does not work as expected - OS X

Users browsing this thread: 1 Guest(s)
jkl
Long time nixers
(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?

--
<mort> choosing a terrible license just to be spiteful towards others is possibly the most tux0r thing I've ever seen
seninha
Long time nixers
Use
Code:
printf 123
instead.

Use printf if you do not want the newline.
jkl
Long time nixers
Ah! Thank you. :)

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

--
<mort> choosing a terrible license just to be spiteful towards others is possibly the most tux0r thing I've ever seen
seninha
Long time nixers
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).
z3bra
Grey Hair Nixers
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).
jkl
Long time nixers
(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. :)

--
<mort> choosing a terrible license just to be spiteful towards others is possibly the most tux0r thing I've ever seen