如何将多行内容分类为 systemd 单元文件中的文件?

How do I cat multi-line content to a file in a systemd unit file?

我正在尝试将文件写入磁盘作为 systemd 单元文件的 ExecStartPre 命令的一部分。

这是我正在使用的:

[Unit]
Description=My service

[Service]
Restart=always
StartLimitInterval=0
ExecStartPre=/usr/bin/cat <<EOFDefaults > /tmp/test
option1=value1
option2=value2
EOFDefaults

ExecStart=/run/some/command

由于这是一个多行命令,我在使用 systemd-analyze verify myservice.service 进行测试时收到以下错误。

所以,我试图转义多行:

[Unit]
Description=My service

[Service]
Restart=always
StartLimitInterval=0
ExecStartPre=/usr/bin/cat <<EOFDefaults > /tmp/test \
option1=value1 \
option2=value2 \
EOFDefaults

ExecStart=/run/some/command

测试单元文件时,出现以下错误:Invalid escape sequences in command line:

作为 systemd 单元文件命令的一部分,如何使用 cat 将多行内容写入文件?

你不知道。 请参阅 Command lines:

上的文档部分

This syntax is intended to be very similar to shell syntax, but only the meta-characters and expansions described in the following paragraphs are understood. Specifically, redirection using "<", "<<", ">", and ">>", pipes using "|", running programs in the background using "&", and other elements of shell syntax are not supported.

您可以通过先调用 shell 来完成此操作,例如:

    ExecStartPre=/bin/sh -c '/usr/bin/cat <<EOFDefaults > /tmp/test \
    option1=value1 \
    option2=value2 \
    EOFDefaults'

然而它变得非常快。

我会做的是将它放在一个单独的 shell 脚本中,然后从服务定义中调用它。一般来说,最好使服务定义尽可能清晰。