在systemd中设置新的环境变量时是否可以引用其他环境变量?
[Service]
EnvironmentFile=/etc/environment
Environment=HOSTNAME=$COREOS_PRIVATE_IPV4
Environment=IP=$COREOS_PRIVATE_IPV4
Environment=FELIX_FELIXHOSTNAME=$COREOS_PRIVATE_IPV4
上面的代码似乎没有用。
答案 0 :(得分:13)
这对unix & linux来说真是一个问题。但仍然是:否,systemd
不会在Environment=
内执行环境变量扩展。来自man systemd.exec
:
Environment=
Sets environment variables for executed processes. Takes a space-separated list of variable assignments. This
option may be specified more than once, in which case all listed variables will be set. If the same variable is
set twice, the later setting will override the earlier setting. If the empty string is assigned to this option,
the list of environment variables is reset, all prior assignments have no effect. Variable expansion is not
performed inside the strings, however, specifier expansion is possible. The $ character has no special meaning.
If you need to assign a value containing spaces to a variable, use double quotes (") for the assignment.
Example:
Environment="VAR1=word1 word2" VAR2=word3 "VAR3=$word 5 6"
gives three variables "VAR1", "VAR2", "VAR3" with the values "word1 word2", "word3", "$word 5 6".
正如您在文档$word
中的示例中看到的那样,只意味着$word
不会执行扩展。 man
所讨论的说明符是%i
,%n
,%u
等。它们位于man systemd.unit
(在他们自己的man
部分下。)
另一方面,ExecStart=
及其衍生物将执行环境变量扩展。在ExecStart=
上使用环境变量是systemd
中额外环境变量的常用解决方法。我相信,这也是其中一个之所以这么多近期程序从环境和命令行参数接受相同参数的原因。
来自ExecStart=
的{{1}}扩展示例:
man systemd.service
Example:
Environment="ONE=one" 'TWO=two two'
ExecStart=/bin/echo $ONE $TWO ${TWO}
This will execute /bin/echo with four arguments: "one", "two", "two", and "two two".
Example:
Environment=ONE='one' "TWO='two two' too" THREE=
ExecStart=/bin/echo ${ONE} ${TWO} ${THREE}
ExecStart=/bin/echo $ONE $TWO $THREE
This results in echo being called twice, the first time with arguments "'one'", "'two two' too", "", and the second
time with arguments "one", "two two", "too".
的文档分布在几个systemd
上,但一段时间后就会习惯它们。