如果我运行此命令
/bin/bash -c 'while true;do /usr/bin/etcdctl set my-container "{\"host\": \"1\", \"port\": $(/usr/bin/docker port my-container 5000 | cut -d":" -f2)}" --ttl 60;sleep 45;done'
Run Code Online (Sandbox Code Playgroud)
我从etcd返回了预期的结果{“主机”:“ 1”,“端口”:49155}
但是如果我把它放在一个systemd文件中
ExecStart=/bin/bash -c 'while true;do /usr/bin/etcdctl set my-container "{\"host\": \"1\", \"port\": $(/usr/bin/docker port my-container 5000 | cut -d":" -f2)}" --ttl 60;sleep 45;done'
Run Code Online (Sandbox Code Playgroud)
我回来了{host:1,port:49155}
为什么文件中的转义符会有所不同?我该如何解决?谢谢!!
小智 7
systemd-escape '\"a fun thing"\'
Run Code Online (Sandbox Code Playgroud)
输出: \x5c\x22a\x20fun\x20thing\x22\x5c
[Service]
ExecStart=/bin/sh -c 'echo "\x5c\x22a\x20fun\x20thing\x22\x5c"'
Run Code Online (Sandbox Code Playgroud)
将打印 a fun thing
简而言之——它是不同的,因为 systemd 执行自己的字符串拆分、转义和扩展,并且它使用的逻辑不符合 POSIX。
你仍然可以做你想做的,但你需要更多的反斜杠:
ExecStart=/bin/bash -c '\
while :; do \
port=$(/usr/bin/docker port my-container 5000 | cut -d: -f2); \
/usr/bin/etcdctl set my-container "{\\\"host\\\": \\\"1\\\", \\\"port\\\": $port}" --ttl 60; \
sleep 45; \
done'
Run Code Online (Sandbox Code Playgroud)
请注意在所需输出中使用\\\"for 每个文字"字符。
顺便说一句——就我个人而言,我建议不要尝试通过字符串连接来生成 JSON——它很容易出现注入漏洞(如果有人可以将他们选择的内容放在docker port命令的输出中,他们可能会将其他键/值对插入到您的数据, "evil": true在port变量中)。使用jq以下方法可以避免此类问题:
ExecStart=/bin/bash -c '\
while :; do \
port=$(/usr/bin/docker port my-container 5000 | cut -d: -f2); \
json=$(jq -nc \
--arg host 1 \
--arg port "$port" \
'{} | .host=$host | .port=($port | tonumber)'); \
/usr/bin/etcdctl set my-container "$json" --ttl 60; \
sleep 45; \
done'
Run Code Online (Sandbox Code Playgroud)
作为一个愉快的副作用,上面避免了需要任何文字双引号字符(唯一使用的是语法到 的副本sh),因此我们不需要任何反斜杠从 systemd 传递到 shell。
Systemd所做的不像您现在所知道的bash那样,因此存在转义问题。实际上,systemd在解析单引号和双引号后会删除它们。这个事实在文档中是正确的(我也是这样做的,然后阅读:D)。
该解决方案将调用一个脚本,该脚本将在您的目的允许的情况下回显您需要的信息(带有转义的引号)。
| 归档时间: |
|
| 查看次数: |
7119 次 |
| 最近记录: |