首页 > 解决方案 > 为什么 echo -n 在 Mac 上的 shell 中不起作用?

问题描述

手册页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.

但是,这似乎不适用于shMac:

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$

标签: bashmacosunixsh

解决方案


-n是. bash_ echo在版本 3.2(随 macOS 一起提供)bash中,当调用为sh. 从 4.0 版开始(其中的某个版本可能在您的 Linux 机器上),bash 调用-nsh.

更新:该xpg_echo选项确定bash's 内置echo是否符合 POSIX。在bash3.2(或至少 3.2 的 macOS 版本)中,此选项默认为 on;在bash4.x 中,它默认为关闭。

% sh -c 'shopt xpg_echo'
xpg_echo        on
% ./sh -c 'shopt xpg_echo'
xpg_echo        off

./sh是一个符号链接/usr/local/bin/bash,在我的机器上本地安装bash4.4。)


推荐阅读