Bash script runs differently in cron than manually launched

Hi,
I’m loosing my mind trying to understand why my simple bash script is running differently when launched manually and launched from crontab.

Script is performing 3 steps:

# STEP 1: remove folders older than 14 days first
find /storage/backup/DBDump -type d -ctime +14 -exec ls -d {} \; >/storage/backup/Temp/foldersToDelete.out
exec < /storage/backup/Temp/foldersToDelete.out
while read item ; do
        if [[ -d $item ]] ; then
                CURRDATE=`date "+%Y-%m-%d %H:%M:%S"`
                rm -rf $item && echo [$CURRDATE] deleted folder: $item >> /storage/backup/Temp/foldersDeleted.out
        fi
done

# STEP 2: create subfolder
CURRDIR=`date "+%Y-%m-%d"`
mkdir /storage/backup/DBDump/$CURRDIR

# STEP 3: dump DB and copy it to the created subfolder
/storage/.kodi/addons/service.mariadb/bin/mysqldump -h<my-NAS-IP> -P3307 -ukodi -p<password> MyMusic72 > /storage/backup/DBDump/$CURRDIR/MyMusic72.sql
/storage/.kodi/addons/service.mariadb/bin/mysqldump -h<my-NAS-IP> -P3307 -ukodi -p<password> MyVideos116 > /storage/backup/DBDump/$CURRDIR/MyVideos116.sql

When launching this script manually all 3 steps are completed.
When that script is added to the crontab then second and third step are completed but the first one is not.
The line launched in cron:

find /storage/backup/DBDump -type d -ctime +14 -exec ls -d {} \; >/storage/backup/Temp/foldersToDelete.out

does not generate the list of folders for deletion!
Output file:

/storage/backup/Temp/foldersToDelete.out

is created but is just empty.

When I launch this single line in SSH:

find /storage/backup/DBDump -type d -ctime +14 -exec ls -d {} \; >/storage/backup/Temp/foldersToDelete.out

then the output file contain the folder that will be deleted.

Why?
Please help!

Do you have entware packages installed too? I assume yes because busybox find doesn’t support -ctime parameter.
You should call find with full path to /opt/bin/find or whatever path it is.

Yes… entware is installed
and indeed it was required to add full path to find, ls and rm commands:

# remove folders older than 13 days first
/usr/bin/find /storage/backup/DBDump -type d -mtime +13 -exec /bin/ls -d {} \; >/storage/backup/Temp/foldersToDelete.out
exec < /storage/backup/Temp/foldersToDelete.out
while read item ; do
        if [[ -d $item ]] ; then
                CURRDATE=`date "+%Y-%m-%d %H:%M:%S"`
                /bin/rm -rf $item && echo [$CURRDATE] deleted folder: $item >> /storage/backup/Temp/foldersDeleted.out
        fi
done

and change -ctime to -mtime as the find in /storage/.opt/bin support -ctime but find in /usr/bin doesn’t.
Problem solved. Thanks vpeter for showing me the right direction. :slight_smile:

1 Like

I’m not sure if you really need full path to any of this 3 commands?

Also you could eliminate temporary file with something like this

/usr/bin/find /storage/backup/DBDump -type d -mtime +13 -exec /bin/ls -d {} \; | while read item ; do