The following code does work when invoked from my shell:
#!/usr/bin/bash
how_many=$(find /home/jerzy/pCloudDrive -type d -iname "CS202*"|wc -l)
#/usr/bin/echo ${how_many} >>/home/jerzy/to.be.removed #This works
if [[ $how_many == 1 ]]; then
exit 0
#echo "There is only one backup of CS. Cannot delete."
elif [[ $how_many == 2 ]]; then
exit 0
#echo "There are only two backups of CS. Cannot delete."
else
#echo "Let us delete"
to_be_removed=$(ls -tr CS202*|grep -m 1 CS202|sed s/://)
/usr/bin/echo "${to_be_removed}" >>/home/jerzy/to.be.removed #empty file is created from cron
/usr/bin/echo "$(ls -tr CS202*|grep -m 1 CS202|sed s/://)" >>/home/jerzy/to.be.removed #empty file is created from cron
#/usr/bin/echo ${to_be_removed} >>/home/jerzy/to.be.removed #empty file is created from cron
#/usr/bin/echo ${to_be_removed} >>/home/jerzy/to.be.removed #"${to_be_removed}" appended from cron
/usr/bin/echo "${to_be_removed}" #when the script is run from my shell it echoes the target directory
/usr/bin/rm -r ${to_be_removed} #works from the shell, not from cron
#/usr/bin/rm -r $(ls -tr CS202*|grep -m 1 CS202|sed s/://) ##works from the shell, not from cron
#/usr/bin/rm -r "${to_be_removed}"
fi
The script is meant to remove the oldest directory that is named like one of them :
CS20210730_1341
CS20210730_2350
CS20210731_2350
The job is to be done once a day, as each day a new CS202*
gets created
by rsync doing my backups.
The lines with echo
are placed in the script only for the sake of debugging.
The code needs not sudo
to remove the specified directory.
It does not work from cron
, i.e. from the crontab of my user jerzy
. When executed from the shell of the same user it does the job, why so?
My environmental variables in my cron:
PATH=/usr/bin:/bin:/usr/sbin:/sbin:/home/jerzy/.cargo/bin
SHELL=/bin/bash
I've diagnosed so far:
rm
does work from cron as/usr/bin/rm -r /home/jerzy//pCloudDrive/CS20210730_1341
when scripted does remove the target. It is not the matter of permissions.- The execution of the script does get started as is proved by
the creation of the file
/home/jerzy/to.be.removed
.
Why doesn't this script work from cron?
find
files in/home/jerzy/pCloudDrive
but thenls -tr CS202*
in the current working directory – steeldriver Aug 01 '21 at 16:38/usr/bin/echo "${to_be_removed}" >> ...
instead of/usr/bin/echo "$to_be_removed >> ..."
? – Jeremy Boden Aug 01 '21 at 16:41ls -tr CS202*
withls -tr /home/jerzy/pCloudDrive/CS202*
solved the issue. It had nothing to do with cron. It was just a coincidence the I was always invoking the program from/home/jerzy/pCloudDrive
- it do not work from other directories, though. – John Smith Aug 01 '21 at 18:03