Unix & Linux
shell-script cron not-root-user which
Updated Sat, 16 Jul 2022 21:33:38 GMT

How to use which command in Crontab?

I would like to make crontab run this script as a regular user:

#!/usr/bin/env bash
if ! test -f ${PIDFILE} || ! kill -s 0 `cat ${PIDFILE}`; then
    `which searchd` --config /home/user/www/wordpress-page/wp-content/uploads/sphinx/sphinx.conf

It simply reruns Sphinx Search daemon, because my shared server kills all my daemons if anything exceeds 1GB of ram (its Webfaction).

When I call that script by hand via CLI command it works, but if I attach it in crontab (using crontab -e) I got an email with an error

which: no searchd in (/usr/bin:/bin)
/home/user/www/wordpress-page/run-searchd.sh: line 8: --config: command not found

Simply which searches root level, but I would like it to behave as called by myself when I log in via ssh as regular user. How to make that happen?


It's probably because of the $PATH. Do this in your shell outside of crontab:

command -v searchd | xargs dirname

This command will return a directory where searchd is on your system or an error if you don't have searchd in your $PATH even in an interactive shell. Now do this at the top of your script you execute in crontab:


Alternatively just use a full path to searchd instead of which searchd.

Also read this on which if you want to fully understand how it works: Why not use "which"? What to use then?.

External Links

External links referenced by this document: