Tuesday, December 1, 2020

Linux - script in command shell v/s triggered from cron

This is another Linux beginner lesson learned when setting up a home NAS using Raspberry Pi. Please skip if the difference between running a command from shell and cron is known.


The below command works fine when running from the command line.

rsync /media/usbseagate1tbc/Media/ /mnt/router/Media -av --progress --delete >> "/var/log/j3dnas/$(date +%F_%H-%M-%S.log)" 2>&1

What this does is that after the rsync command completed, it redirects the output to a file where the file name has the date details.

The idea is to get the daily log of how the files are backed up to an external hard disk connected to the router. The source is the hard disk connected to RasPi which is exposed to the home network as a share. 

When I added this command to cron, it was not working.


The issue here is with the $(Date... this is a shell feature. When running the command from cron, it is not a shell and don't get the shell features. What we need to do is to wrap the commands in a .sh file and add the file name to cron as follows

0 1 * * * /usr/local/bin/nassync.sh
It is a known thing in the Linux world. It took me some time to google it with the right terms but finally got it on the internet

No comments: