Gno*_*ght 4 linux bash centos brace-expansion systemd
以下测试是在 CentOS 7.1 中进行的。
创建以下文件test.service中/usr/lib/systemd/system/
[Unit]
Description=Test Bash Brace Expansion
Wants=network.target
After=network.target
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/bin/bash -c "a='hello world'; echo ${a}"
[Install]
WantedBy=multi-user.target
Run Code Online (Sandbox Code Playgroud)
并执行 systemctl daemon-reload; systemctl restart test; systemctl status test -l
没有值的输出,因为${a}不作为词替代hello world,直到它echo ${a}变成
echo $a : 工作 echo $${a}: 工作这$$意味着 aa bash 中进程的 pid,但是为什么可以通过$$这个技巧ExecStart来获得这个词hello world呢?
您正在做的不是大括号扩展,而是参数扩展。大括号扩展(例如${1..5}在双引号内不起作用。
参数扩展在双引号内确实有效,但是如果替换应该发生在被调用的 shell 而不是当前的 shell 中,则$需要引用符号。
考虑这个例子:
a='bye world' ; /bin/bash -c "a='hello world'; echo ${a}"
bye world
Run Code Online (Sandbox Code Playgroud)
与这个:
a='bye world' ; /bin/bash -c "a='hello world'; echo \${a}"
hello world
Run Code Online (Sandbox Code Playgroud)
重要的是要记住,你的 systemd 服务描述文件不是在 Bash 中执行的(如上例所示),因此有一些非常相似但略有不同的规则,请参阅服务单元配置文件的文档。
您的问题是,就像上面第一个示例中的交互式 Bash 一样,systemd 正在尝试扩展${a}它在其环境中没有的功能。正如您已经注意到的,$$是您的解决方案,上面的链接解释了原因:
要传递文字美元符号,请使用“$$”。
这允许参数扩展发生在 systemd 正在调用的 Bash shell 中。所以配置文件中的行应该是:
ExecStart=/bin/bash -c "a='hello world'; echo $${a}"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2451 次 |
| 最近记录: |