Set PATH for a systemd unit
Solution 1
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
.
Solution 2
Unless you're using Environment=
, EnvironmentFile=
or PassEnvironment=
, you should be using ExecSearchPath=
.
man systemd.exec
says concerning ExecSearchPath=
:
Takes a colon separated list of absolute paths relative to which the executable used by the Exec*= (e.g. ExecStart=, ExecStop=, etc.) properties can be found. ExecSearchPath= overrides $PATH if $PATH is not supplied by the user through Environment=, EnvironmentFile= or PassEnvironment=. Assigning an empty string removes previous assignments and setting ExecSearchPath= to a value multiple times will append to the previous setting.
Related videos on Youtube
Agrajag9
Updated on September 18, 2022Comments
-
Agrajag9 over 1 year
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
withPATH=/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
withexport 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. -
Agrajag9 about 7 yearsIf I wrap the command this way AND use the profile.d file (I want the path added for login shells as well), would I still need to set the path in ExecStart? Or will that read from profile.d?
-
meuh about 7 yearsI think you will still need to set the PATH in the ExecStart. The bash will probably only read from profile.d if it is a login shell. You could try adding
--login
before the-c
to force this instead of settting the PATH, but you will be making bash run lots of setup that might not work well in the bare systemd environment, and give you errors in the journal log. -
Admin almost 2 yearsNote that 'ExecSearchPath' was added in systemd 250, so if your distro doesn't have that version (or newer) it's not available to you.