Cron jobs run in their owner's home directory When cron jobs are invoked they are run as the user who owns them.
Use cd . If you ask for the answer not to use cd because you've tried it and it didn't work, it's likely you didn't enter it correctly in the crontab. The simplest way would be to write a small shell script that will cd and run your main task, then cron the script.
When you create a crontab file, it is automatically placed in the /var/spool/cron/crontabs directory and is given your user name. You can create or edit a crontab file for another user, or root, if you have superuser privileges. Enter crontab command entries as described in "Syntax of crontab File Entries".
All jobs are executed by a shell, so start that shell snippet by a command to change the directory.
cd /path/to/directory && ./bin/myapp
Concerning the use of &&
instead of ;
: normally it doesn't make a difference, but if the cd
command fails (e.g. because the directory doesn't exist) with &&
the application isn't executed, whereas with ;
it's executed (but not in the intended directory).
Reading man 5 crontab
should tell you that there's a HOME
variable set which can be redefined in the file. It becomes your working directory. You can set PATH
for the command(s) too. Of course this affects all the cron schedule lines.
E.G.
Several environment variables are set up automatically by the cron(8) daemon.
SHELL
is set to/bin/sh
, andLOGNAME
andHOME
are set from the/etc/passwd
line of the crontab´s owner.HOME
andSHELL
can be overridden by settings in the crontab;LOGNAME
can not.(Note: the
LOGNAME
variable is sometimes calledUSER
onBSD
systems and is also automatically set).
Depending on your cron of course, but mine also has MAILTO
, MAILFROM
CONTENT_TYPE
, CRON_TZ
, RANDOM_DELAY
, and MLS_LEVEL
.
So for your hypothetical app I'd recommend a file name /etc/cron.d/hypothetical
containing:
# Runs hypothetical app @ 00:01Z in its local path for reading its config or something.
SHELL=/bin/sh
HOME=/where/the/app/is
PATH=/where/the/app/is:/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
CRON_TZ=UTC
1 0 * * * theappuser hypothetical --with arguments
For example with docker-compose
relying on the cwd docker-compose.yml
:
SHELL=/bin/sh
HOME=/path/to/composed-app
5 5 * * * root docker-compose restart -t 10 service-name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With