Does systemd allow this Environment in a service file?


meaning I'd to set abc as abc if abc exist, if not set abc to notABC?

Can systemd do this?


No, this is not possible in systemd unit files, it only supports minimal variable expansion and doesn't really aim to implement shell-like variable substitution.

If you need something like what you describe, the recommendation would be to wrap your initialization into a shell script and use that script in your ExecStart=, in which case you'll have all features of a shell available to set environment variables before you execute the service's main program.

If you use a shell script in ExecStart=, then make sure you use exec to launch the main program at the end of the script, so the shell gets out of the way and systemd is directly monitoring your command.

If you want to avoid having to create and maintain an additional external file, you can inline the shell script within the unit file, but in that case keep in mind that you need to call the shell explicitly (with sh -c or equivalent for another shell) and that you need to escape the $ (by using two of them) to prevent systemd from trying to interpret it. So you need something like:

ExecStart=/bin/sh -c 'abc=$${abc:-"notABC?"}; exec mycmd "$abc"'
  • 1
    Thanks, then can I put something like this ExecStart= exec <...> ${abc:-'notABC?'}? – Tuyen Pham Nov 2 '18 at 11:58
  • 1
    It gets tricky, but can be done... You need to call the shell explicitly (with sh -c ...) and you need to escape the $ so systemd doesn't try to parse it. Putting it together: ExecStart=/bin/sh -c 'abc=$${abc:-"notABC?}"; exec mycmd "$abc"' – filbranden Nov 2 '18 at 12:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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