[英]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.