Bash-script as linux-service won't run, but executed from terminal works perfectly

I have custom script to mount google drives.
Part of this script, is following code:

if [ ! "$(which google-drive-ocamlfuse)" ]
then
    echo "Install google-drive-ocamlfuse first!"
    exit 1
fi

Executed from terminal, works like charm.
So, I configured it as service:

[Unit]
Description=Mount and umount google drives

[Service]
User=<usernamehere>
Type=oneshot
RemainAfterExit=true
ExecStart=/home/<usernamehere>/mybscripts/gdrivemounter.sh -m
ExecStop=/home/<usernamehere>/mybscripts/gdrivemounter.sh -u
Environment="DISPLAY=:0"
Environment="XAUTHORITY=/home/<usernamehere>/.Xauthority"

[Install]
WantedBy=graphical.target

Unfortunately, I see exit code: "Install google-drive-ocamlfuse first!" when I checking service status.

Command which google-drive-ocamlfuse under user and root gives me valid path:

$ which google-drive-ocamlfuse
/home/<usernamehere>/.opam/default/bin/google-drive-ocamlfuse

Where is the problem?


The problem is that, when the script runs as a service, it does not run as "you": it does not have your environment. Specifically, it does not have your PATH variable.

Either add /home/<usernamehere>/.opam/default/bin to the PATH in your script, or simply hardcode the full path for that program.


The most likely reason is that the directory containing google-drive-ocamlfuse is in the PATH of your login shell, but not in the standard PATH used by systemd.

Just add a line like this at the beginning of your script:

PATH=$PATH:/path/to/google-drive-ocamlfuse

Thank you all for solutions. Each is important for me and helpful - again I learned something new. At the end I decided to install google-drive-ocamlfuse from deb, instead via opam. It is better to install gdo in path available for all users. Due to this, additional configuration of $PATH is not necessary.


Note: I've left this answer 'as is' but the only relevant part is how to set the environment via the service file, rather than directly in the script. Setting a new $PATH in the script won't persist after the script has finished running.

In reference to the other answers, please don't pollute your $PATH by editing your script, when in fact it works if ran by the correct user. If you must edit it directly in the script, put it back after by restoring the original $PATH.

I think the issue lies with the fact that /etc/profile isn't processed by systemd services, and so it hasn't for whatever reason got access (or an updated $PATH) for the executable required.

To test this you could echo out $PATH within the error block, and if it IS missing, then add it directly into the Environment variable within the systemd service file:

[Service]
Environment=PATH=/home/someUser/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

This way, the path is only updated for the script while it runs, it doesn't modify it for users who might not expect it to be modified..