6

I am trying to write a file to disk as part of the ExecStartPre command of a systemd unit file.

This is what I am using:

[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

Since that's a multi-line command, I get the following error when testing it with systemd-analyze verify myservice.service.

So, I tried to escape the multi-lines:

[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

When testing the unit file, I get the following error: Invalid escape sequences in command line:

How does one use cat to write multi-line content to a file as part of a systemd unit file command?

1 Answer 1

8

You don't. See the documentation section on 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.

You might be able to do this by calling a shell first with something like:

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

However it becomes cluttered really fast.

What I would do, is to put this in a separate shell script and call that from the service definition. In general is is best to keep the service definition as clear as possible.

2
  • Tried calling a shell from ExecStarPre, but it didn't work. Ended up using a shell script.
    – F21
    Commented Sep 8, 2015 at 23:47
  • 3
    @F21 It also needs an \n before each trailing \ , because otherwise the lines are just concatenated into one line. Also consider removing the extraneous space before the trailing \ , which will otherwise end up in the here-doc and might become a hard-to-find bug if it causes problems. Commented Mar 28, 2019 at 7:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.