【问题标题】:Referencing Other Environment Variables in Systemd在 Systemd 中引用其他环境变量
【发布时间】:2016-10-18 07:31:43
【问题描述】:

在systemd中设置新环境变量时是否可以引用其他环境变量?

[Service]
EnvironmentFile=/etc/environment
Environment=HOSTNAME=$COREOS_PRIVATE_IPV4
Environment=IP=$COREOS_PRIVATE_IPV4
Environment=FELIX_FELIXHOSTNAME=$COREOS_PRIVATE_IPV4

上面的代码似乎不起作用。

【问题讨论】:

  • 我投票结束这个问题,因为它更适合 Unix 和 Linux 站点。它与编程没有直接关系。 unix.stackexchange.com

标签: systemd


【解决方案1】:

这确实是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= 中的扩展示例,来自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 的文档分布在多个 man 中,但一段时间后就会习惯它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-13
    • 1970-01-01
    • 2019-05-15
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 2019-09-02
    相关资源
    最近更新 更多