bash - 为什么 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.
但是,这似乎不适用于sh
Mac:
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$
解决方案
-n
是. bash
_ echo
在版本 3.2(随 macOS 一起提供)bash
中,当调用为sh
. 从 4.0 版开始(其中的某个版本可能在您的 Linux 机器上),bash
在调用-n
为sh
.
更新:该xpg_echo
选项确定bash
's 内置echo
是否符合 POSIX。在bash
3.2(或至少 3.2 的 macOS 版本)中,此选项默认为 on;在bash
4.x 中,它默认为关闭。
% sh -c 'shopt xpg_echo'
xpg_echo on
% ./sh -c 'shopt xpg_echo'
xpg_echo off
(./sh
是一个符号链接/usr/local/bin/bash
,在我的机器上本地安装bash
4.4。)
推荐阅读
- ruby - Bundler 不允许在项目主目录中使用 gems
- algorithm - 在更大的矩形中组合矩形
- angular - Angular 7 - 函数调用指令
- reactjs - 不能在一行上设置三个项目
- android - Android:recyclerview 上默认选择的项目
- node.js - 找不到带有可执行指南针的 gem 指南针 (>= 0.a)
- python - 使用 Python 3.7 Anaconda 将 PDF 转换为 CSV
- solr - 如何在 Solr 中查询字符串字段
- sql-server - 由于文件组“DEFAULT”中的磁盘空间不足,无法为数据库“TEMPDB”分配新页面
- split - 如何在回车符 (\r) 或 CRLF (\r\n) 行终止符上拆分流?