How to control where script run by cron saves files

cronperl

I've got the following cron job that runs at 6 am every morning:

00 6 * * * /Users/username/path/to/script/wget.pl 1;

The script, written in perl, fetches the latest files from a website.

Within the perl script, the path gets changed with:

`cd '/path/to/directory'`

However, all the files downloaded aren't getting saved to /path/to/directory they get saved in /Users/username.

What can I do to get the script to save it in the directory I want?

Best Answer

Doing a `cd /path` within your script only changes the directory for the shell that is spawned to execute the shell command. It's the same thing as doing

system('cd /path');

It doesn't change the cwd (current working directory) of the script itself. The best way to do it is to have your script write the files to a specific directory. If your perl script is a straight wrapper for wget, you can do away with the perl script and do something along the lines of:

wget -O /full/path/to/file http://host/url/here

If you want to do this within perl (example idea, not tested)...

use LWP::Simple qw(get);
my $url = 'http://host/url/here';
my $result = get $url;
open(my $fh, ">", "/path/to/file");
print $fh $result;
close($fh)

One final option (again not tested)...

00 6 * * * cd /path/you/want;/Users/username/path/to/script/wget.pl 1;