如何确定 systemd EnvironmentFile 将设置的精确环境变量集?
How can I determine the precise set of environment variables a systemd EnvironmentFile would set?
systemd 有 an EnvironmentFile
directive,它根据许多规则从文件内容设置环境变量,完全 等同于 shell 将解析该文件。
如何在 中完全 解析 systemd EnvironmentFile
与 systemd 本身相同的方式?
最可靠的方法是让 systemd 通过瞬时服务自行解析文件。因此:
# 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 "$@")
}
此后,可以调用(作为示例):
newVarsForFile_shellscript /etc/conf.d/*.conf
...发出一个 shell 脚本片段,当由 bash 执行时,将设置所有相同的环境变量,将相关的 EnvironmentFile
添加到服务定义会设置。
systemd 有 an EnvironmentFile
directive,它根据许多规则从文件内容设置环境变量,完全 等同于 shell 将解析该文件。
如何在 中完全 解析 systemd EnvironmentFile
与 systemd 本身相同的方式?
最可靠的方法是让 systemd 通过瞬时服务自行解析文件。因此:
# 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 "$@")
}
此后,可以调用(作为示例):
newVarsForFile_shellscript /etc/conf.d/*.conf
...发出一个 shell 脚本片段,当由 bash 执行时,将设置所有相同的环境变量,将相关的 EnvironmentFile
添加到服务定义会设置。