为什么在Mac的Shell中无法回显-n?

时间:2018-11-21 18:39:35

标签: bash macos unix sh

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$

1 个答案:

答案 0 :(得分:3)

-nbash的{​​{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。)