Consul-template中如何展开环境变量中的换行符?
问题
希望在consul-template中传入包含换行符的环境变量并使其展开,例如将"hello\nworld"显示为:
hello world
执行命令:
VARIABLE="hello\nworld" consul-template -template "in.tpl:out.txt" -once && cat out.txt
模板文件in.tpl内容为:
{{ env "VARIABLE" }}
但实际得到的结果是:
hello\nworld
调试模板时执行{{ env "VARIABLE" | spew_dump }},得到:
"hello\\nworld"
即\n被转义为\\n,请问如何解决该问题?
解决方法
方法一:传递环境变量时直接传入真实换行符
当前shell会把"hello\nworld"里的\n视为普通字符,而非换行符。可通过以下方式传递包含真实换行的环境变量:
- Bash/Zsh等shell:使用ANSI-C引号(
$'')定义变量,让shell自动解析\n为换行:
VARIABLE=$'hello\nworld' consul-template -template "in.tpl:out.txt" -once && cat out.txt
- POSIX兼容shell:直接输入换行(按下Enter键)定义变量:
VARIABLE="hello world" consul-template -template "in.tpl:out.txt" -once && cat out.txt
方法二:在模板中解析转义字符
如果无法修改环境变量的传递方式,可在consul-template模板里使用unescape过滤器解析转义的换行符:
修改in.tpl内容为:
{{ env "VARIABLE" | unescape }}
unescape过滤器会将字符串中的\\n转换为真实换行符,输出结果即可正确展开换行。
内容的提问来源于stack exchange,提问作者henry.oswald
相关产品推荐
相关产品推荐

