[systemd-devel] Problem expanding environment variables

Andrei Borzenkov arvidjaar at gmail.com
Fri Sep 6 09:04:06 UTC 2024


On Fri, Sep 6, 2024 at 11:24 AM Thomas Köller <thomas at koeller.dyndns.org> wrote:
>
> I am having problems expanding environment variables in a service file.
> This test serivice illustrates the problem:
>
> root at yoga:/etc/systemd/system# cat varexp.service
> [Unit]
> Description = Test environment variable expansion
>
> [Service]
> Type = oneshot
> Environment = "VAR=abc-xyz"
> ExecStart = sh -c 'echo Res: ${VAR#abc-}'
>
> Running it yields the following result:
>
> root at yoga:/etc/systemd/system# systemctl status varexp.service
> ○ varexp.service - Test environment variable expansion
>       Loaded: loaded (/etc/systemd/system/varexp.service; static)
>      Drop-In: /usr/lib/systemd/system/service.d
>               └─10-timeout-abort.conf
>       Active: inactive (dead)
>
> Sep 06 10:17:16 yoga systemd[1]: Starting varexp.service - Test
> environment variable expansion...
> Sep 06 10:17:16 yoga (sh)[8541]: varexp.service: Invalid environment
> variable name evaluates to an empty string: VAR#abc-
> Sep 06 10:17:16 yoga sh[8541]: Res:
> Sep 06 10:17:16 yoga systemd[1]: varexp.service: Deactivated successfully.
> Sep 06 10:17:16 yoga systemd[1]: Finished varexp.service - Test
> environment variable expansion.
>
> According to the output lines above, it is the shell that complains.

No, this message comes from systemd.

> However, running the command from an interactive shell yields the
> expected result:
>
> root at yoga:/etc/systemd/system# VAR='abc-xyz' sh -c 'echo ${VAR#abc-}'
> xyz
>
> What is wrong here?
>
>

You need to quote $ to pass it to the shell.

ExecStart = sh -c 'echo Res: $${VAR#abc-}'


More information about the systemd-devel mailing list