echo
的手册页上说:
-n Do not print the trailing newline character. This may also be
achieved by appending `\c' to the end of the string, as is done by
iBCS2 compatible systems. Note that this option as well as the
effect of `\c' are implementation-defined in IEEE Std 1003.1-2001
(``POSIX.1'') as amended by Cor. 1-2002. Applications aiming for
maximum portability are strongly encouraged to use printf(1) to
suppress the newline character.
但是,在Mac上的sh
中,这似乎不起作用:
sh-3.2$ echo $0
/bin/sh
sh-3.2$ which echo
/bin/echo
sh-3.2$ echo -n foo
-n foo
它在bash
中正常工作:
bash-3.2$ echo $0
bash
bash-3.2$ which echo
/bin/echo
bash-3.2$ echo -n foo
foobash-3.2
FWIW这似乎仅在Mac上发生,在Linux上正常运行:
$ echo $0
sh
$ echo -n foo
foo$
答案 0 :(得分:3)
-n
是bash
的{{1}}扩展。在3.2版(macOS附带)中,echo
在以bash
调用时不支持扩展。从版本4.0(某些版本可能在您的Linux机器上开始)开始,sh
会以bash
的身份被授予-n
的荣誉。{p>
更新:sh
选项确定xpg_echo
的内置bash
是否符合POSIX。在echo
3.2(或至少是3.2的macOS构建)中,此选项默认为on;在bash
4.x中,它默认为关闭。
bash
({% sh -c 'shopt xpg_echo'
xpg_echo on
% ./sh -c 'shopt xpg_echo'
xpg_echo off
是指向./sh
的符号链接,/usr/local/bin/bash
是我计算机上本地安装的bash
4.4。)