Am Freitag, dem 06.09.2024 um 10:18 +0200 schrieb Thomas Köller:
> I am having problems expanding environment variables in a service file.
> This test serivice illustrates the problem:
>
> `root@yoga:/etc/systemd/system# cat varexp.service`
>
> ```ini
> [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@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.
> However, running the command from an interactive shell yields the
> expected result:
>
> `root@yoga:/etc/systemd/system# VAR='abc-xyz' sh -c 'echo ${VAR#abc-}'`
> ```bash
> xyz
> ```
>
> What is wrong here?
Hi Thomas,
`systemd` is trying to interpolate the variable `${VAR#abc-}` first before giving it to your `ExecStart=`.
Use `$${VAR#abc-}` instead.
BR
Silvio