Various Articles

TIL: Cronjobs and absolute paths

In the TIL series, where I share information everyone else but me already knew, I stumbled on a problem today on a e-Commerce installation.

Before you panic and say “Not another rant about Magento!”, relax. The problem was related to a script I’ve programmed, a bash script that moved, edited and copied files. At least, that’s what the file was supposed to do every 15 minutes in theory.

In reality, the script never really worked when run from the cronjob. If I ran it manually from the command line there doesn’t seem to be a problem.

The culprit was that I was using relative paths in the script. Not really a problem when you run it from the terminal and first cd something/something for a bit. Quite the problem when you’re running it from a cronjob, apparently, as all commands were looking for “folders that don’t exist”.

The lesson I learned today is that you want to use absolute paths for scripts that you run through a cron job. So, for example

cp /usr/home/somedude/import/*.jpg /usr/home/somedude/media

… will work just fine when run from a cronjob, whereas a script with

 cp ../import/*.jpg ../media 

… would fail miserably.

On a related note, I also discovered the ln command. With ln -s you can create a “symbolic link” to a folder. If, for example, typing

cd /usr/home/somedude/scripts/export/php/ 

is too long, you can use

 ln -s /usr/home/somedude/scripts/export/php/ /shortlink 

… so you can use /shortlink as a replacement of the long-ass directory path.



Categories: Various Articles