Surely there must be a way to specify the "current directory" from the Crontab command?
The way to specify the working directory for a cron job is to use the cd
command within the job to change to the correct working directory:
5 * * * * cd /path/to && java -jar timeline.jar
Cron jobs are run using the shell, so you can use shell syntax within the job. The job here is a sequence of two commands, the cd
command and the java
command. The '&&' means that the second command (java) runs only if the first command (cd) succeeds.
In the general case, depending on the command being run you may need to set environment variables, change the working directory, or redirect standard output and standard error within the cron job. You can do all these things in shell one-liners. But personally, I try to avoid having complicated shell commands in the crontab file. If I need to do something complex in a crontab, I'll write a shell script and have cron run the script:
#!/bin/bash
cd /path/to && java -jar timeline.jar
...
5 * * * * /home/jdoe/bin/launch-timeline-jar.sh
This is admittedly a little overkill for the case at hand. But suppose you needed to set the command PATH, and you want to capture the program's error messages in a log file, and you want to add a timestamp to the log file so you can know which run produced which errors. It's much easier to express all of these things within a shell script than directly within the crontab file:
#!/bin/bash
PATH=/some/path/bin:${PATH} # Set our PATH
cd /path/to || exit 1 # Set the working directory
exec >> timeline.log 2>&1 # Direct output to a logfile
date # Write a timestamp to the log
exec java -jar timeline.jar # Launch the command we came here for