本文介绍了如何确定systemd EnvironmentFile可以设置的精确环境变量集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

systemd具有一个 EnvironmentFile 指令,该指令根据许多规则从文件的内容设置环境变量,这些规则与外壳解析该文件的方式相当不相同.

systemd has an EnvironmentFile directive, which sets environment variables from a file's contents based on a number of rules, which are not quite equivalent to how a shell would parse that file.

我该如何像使用systemd本身一样准确地解析 中的systemd EnvironmentFile ?

How can I parse a systemd EnvironmentFile in exactly the same way that systemd itself would?

推荐答案

最确定的事情是让systemd通过临时服务解析文件本身.因此:

The surest thing is to let systemd parse the file itself, via a transient service. Thus:

# emit a NUL-delimited set of key=value definitions for environment variables defined by a set of files
newVarsForFile_nullsep() {
  local -a extraParams=( ); local file
  (( $# )) || return 0 # no files specified, nothing to do
  for file in "$@"; do
    extraParams+=( --property=EnvironmentFile="$file" )
  done
  comm -z -23 \
    <(sort -z < <(systemd-run --user --pipe "${extraParams[@]}" grep -zvE '^INVOCATION_ID=' /proc/self/environ </dev/null)) \
    <(sort -z < <(systemd-run --user --pipe grep -zvE '^INVOCATION_ID=' /proc/self/environ </dev/null) )
}

# emit code that can be eval'd in an instance of bash to precisely define the exact variables
newVarsForFile_shellscript() {
  while IFS= read -r -d '' vardef; do
    printf '%s=%q\n' "${vardef%%=*}" "${vardef#*=}"
  done < <(newVarsForFile_nullsep "$@")
}

此后,可以调用(作为示例):

Thereafter, one may invoke (as an example):

newVarsForFile_shellscript /etc/conf.d/*.conf

...发出一个shell脚本片段,当由bash执行该片段时,它将设置所有与将相关 EnvironmentFile s添加到服务定义中相同的环境变量.

...to emit a shell script fragment which, when executed by bash, will set all the same environment variables that adding the relevant EnvironmentFiles to a service definition would set.

这篇关于如何确定systemd EnvironmentFile可以设置的精确环境变量集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 03:36