Systemd ExecStart中的Bash Brace扩展

时间:2015-10-13 08:03:38

标签: linux bash centos systemd brace-expansion

以下测试在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

并执行systemctl daemon-reload; systemctl restart test; systemctl status test -l

由于${a}未替换为hello world字,因此没有值的输出,直到将echo ${a}更改为

为止
  1. echo $a:工作
  2. echo $${a}:工作
  3. $$表示bash中进程的pid,但为什么$$可以在ExecStart中执行该操作来获取单词hello world

1 个答案:

答案 0 :(得分:3)

支撑与参数扩展

您正在做的不是支撑扩展,而是参数扩展。支撑扩展(例如<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 在双引号内不起作用。

使用两个Bash shell解释您的问题

参数展开 在双引号内工作,但如果替换应在被调用的shell而不是当前的shell中进行,则需要引用${1..5}符号。

考虑这个例子:

$

VS。这一个:

a='bye world' ; /bin/bash -c "a='hello world'; echo ${a}"
bye world

将解决方案应用于systemd服务文件以及为什么`$$`工作

重要的是要记住你的系统服务描述文件没有在Bash中执行(如上例所示),因此有一些非常相似但略有不同的规则,请参阅documentation for service unit configuration files

你的问题是,就像上面第一个例子中的交互式Bash一样,systemd正在尝试扩展它在环境中没有的a='bye world' ; /bin/bash -c "a='hello world'; echo \${a}" hello world 。正如您已经注意到的那样,${a}是您的解决方案,上面的链接解释了原因:

  

要传递文字美元符号,请使用&#34; $$&#34;。

这允许参数扩展发生在系统调用的Bash shell中。所以配置文件中的行应为:

$$