Systemd – How to Set PATH for a systemd Unit on CentOS

centospathsystemd

How does one set the PATH for non-login shells in CentOS 7?

Specifically, I have a systemd unit that needs binaries in /usr/local/texlive/2016/bin/x86_64-linux.

I attempted to set it in /etc/environment with PATH=/usr/local/texlive/2016/bin/x86_64-linux:$PATH but then my PATH was /usr/local/texlive/2016/bin/x86_64-linux:$PATH:/usr/local/sbin:/usr/sbin.

I created /etc/profile.d/texlive.sh with export PATH="/usr/local/texlive/2016/bin/x86_64-linux:${PATH}" but that only worked for login shells.

I looked at Set Path for all Users (Login and Non-login Shells) but the solution was already attempted above.

I looked at How to add a path to system $PATH for all users's non-login shell and login shell on debian but there's no accepted solution and I'm not sure I want to modify /etc/login.defs because it might get changed in an update.

Best Answer

The simplest answer is to set the PATH as part of your ExecStart command in the systemd Unit file. For example, if you currently have

ExecStart=/bin/mycmd arg1 arg2

then change it to

ExecStart=/bin/bash -c 'PATH=/new/path:$PATH exec /bin/mycmd arg1 arg2'

The expansion of $PATH will be done by bash, not systemd. Alternatives such as using Environment=PATH=/new/path:$PATH will not work as systemd will not expand the $PATH.

Related Question