As the title explains, I'd need to take a file and put it into a zip archive once a day; also, the zip file has to be moved in /var/www/html, where a .php scripts allow users to download it.
Assuming this:
- the absolute path of the file is
/home/myuser/working-directory/file.txt - I put all scripts file I need to run using cronjobs in
/usr/scripts - I programmed the following cronjob using
sudo crontab -e, instead ofcrontab -ebecause /var/www/html needs administrative privileges
The results of my thoughts are the followings:
create-zip.sh
#!/bin/bash
cp /home/myuser/myworkingdir/file.txt /home/myuser/file.txt && cd /home/myuser && zip my-zip-file-$(date "+%b_%d_%Y_%H.%M.%S").zip file.txt && rm file.txt && rm /var/www/html/my-zip-file*.zip && mv my-zip-file*.zip /var/www/html && cdsudo crontab -e
@daily sh /usr/scripts/create-zip.shWell.. it doesn't work. I think that the problem is something related with privileges because I get file.txt copied in /home/myuser , and also the zip is created. But then i can't get the zip moved to /var/www/html, even if the crontab is running under Root privileges.
Any idea?
Also..since a .zip is created once a day, I'd need to remove the previous .zip from /var/www/html before move the new one in there. I tried using
rm /var/www/html my-zip-file-*.zip(check the create-zip.sh above) but it doesn't work too.. so I guess it's something wrong with privileges. /var/www/html is into the group www-data and its owner too is www-data.
61 Answer
Joining commands with && means that the command on the right will only run if the one on the left was successful. This means that your crontab will fail the first time it is run since there is no zip file in /var/www/html/ so the rm /var/www/html/my-zip-file*.zip fails and the mv will not be executed.
So, you can either create a file of the right name that can be deleted and keep the same cron command:
touch /var/www/html/my-zip-file.zipOr, you can use ; instead of &&:
cp /home/myuser/myworkingdir/file.txt /home/myuser/file.txt &&
cd /home/myuser &&
zip my-zip-file-$(date "+%b_%d_%Y_%H.%M.%S").zip file.txt &&
rm file.txt &&
rm /var/www/html/my-zip-file*.zip ;
mv my-zip-file*.zip /var/www/html && cdYou are also making this way more complex than it needs to be. The copying of /home/myuser/myworkingdir/file.txt to /home/myuser/file.txt is unnecessary since you're only using that to zip it and then are deleting it. The cd commands are not needed, you can use the full path. There's also no reason to cd at the end. All you need is one command to remove any zip files from the target directory and one command to zip them:
rm /var/www/html/my-zip-file*.zip && zip /var/www/htmlmy-zip-file-$(date "+%b_%d_%Y_%H.%M.%S").zip /home/myuser/myworkingdir/file.txt 2