Systemd – How to Execute chdir Before Starting a Service

systemd

Question: Can I kick off a process with systemd and assign that process a working directory of my choosing?

I have a service that I want to start with systemd. When that service is being started, I want to be able to assign it a current working directory. I know how to do this if I was using init, but I'm having trouble with systemd.

Here's what I've been trying to get working.

My Service

I created a simple utility ("listdir"), written in Python, and placed in /opt/bin/listdir:

#! /usr/bin/python

import os

print 'Current working directory: %s' % (os.getcwd())

My Configuration File

I then created a listdir.service file for systemd and placed it here: /lib/systemd/system/listdir.service:

[Unit]
Description=Test of listing CWD.

[Service]
ExecStartPre=chdir /usr/local
ExecStart=/opt/bin/listdir
StandardOutput=syslog
StandardError=syslog

[Install]
WantedBy=multi-user.target

Problem

When I run systemctl start listdir my system log records the root directory ("/") as the current working directory. Of course, I expected /usr/local as the current directory, since I thought ExecStartPre would change directories before starting the process.

Obviously, I'm imagining that systemd would work something like a shell script (even though I know it isn't a shell script). Can someone give me an idea of what I should be doing? Is it even possible to set a working directory using systemd? Thanks!


Edit: My system log is reporting an error. (I just noticed.)

Executable path is not absolute, ignoring: chdir /usr/local 

So, chdir is a shell command, and not an executable itself. Okay. But is there still some way for me to change directories using systemd?

Best Answer

On systemd >= 227 you should be able to use:

[Service]
WorkingDirectory=/usr/local

to get your script to execute there.

(DOCS)

Related Question