简体   繁体   English

echo在/ bin / sh和/ bin / bash之间打印“ \\ n”的方式有所不同

[英]echo prints “\n” differently between /bin/sh and /bin/bash

I have a shell script that reads a multi-line JSON string from cURL: 我有一个Shell脚本,可以从cURL读取多行JSON字符串:

r=$(curl -H "X-Vault-Token: $VAULT_TOKEN" -fs $VAULT_ADDR/v1/$1)

If I run echo $r and execute the script with /bin/sh I see that newline characters inside the JSON are interpreted as newlines: 如果运行echo $r并使用/bin/sh执行脚本,我会发现JSON中的换行符被解释为换行符:

{"data": {"value": "foo
bar"}}

but when I execute the script with /bin/bash the newlines are literal: 但是当我用/bin/bash执行脚本时,换行符是原义的:

{"data": {"value": "foo\nbar"}}

I'd like the newline to be literal when using either /bin/sh and /bin/bash . 我希望使用/bin/sh/bin/bash时,换行符是原义的。 How do I stop /bin/sh from interpreting the newlines? 如何停止/bin/sh解释换行符?

file -h /bin/sh
/bin/sh: symbolic link to dash

Use printf instead of echo . 使用printf代替echo

printf '%s\n' "$r"

From the POSIX spec for echo : POSIX规范中获取echo

It is not possible to use echo portably across all POSIX systems unless both -n (as the first argument) and escape sequences are omitted. 除非-n(作为第一个参数)和转义序列都被省略,否则不可能在所有POSIX系统上都可移植地使用echo。

Reading the APPLICATION USAGE section in full is strongly recommended. 强烈建议您完整阅读“应用程序使用情况”部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM