I have a script that scans all the directories and subdirectories for those with "RC" in their name and delete all older then 40 days but always leave the last one even if it is older than 40 days.
The problem I am heaving is that if I run the script by hand ./cronJob.sh it works as it should. But when I put it on a crontab list it does not delete directories, but only outputs two lines in log.
#!/bin/bash
datum=$(date -I)
MOUNTLOG=/var/log/softwareRC/
FIND=/bin/find;
deleteDir(){
echo "-------- START $parent --------" >> $MOUNTLOG/$datum.log
dname=$(/usr/bin/dirname $1)
temp="${dname%\s.*}"
temp=(${temp[@]})
parent="${temp[0]}"
dirNum="$($FIND $parent -maxdepth 1 -name *RC* -type d -print | wc -l)"
najnovejsi="$($FIND $parent -maxdepth 1 -name *RC* -type d -print | sort | tail -n 1)"
if [ $dirNum -gt 1 ]; then
$FIND "$parent" -path "$najnovejsi" -prune -o -name *RC* -mtime +40 -print -exec rm -r "{}" \; >> $MOUNTLOG/$datum.log
fi;
echo "-------- END $parent --------" >> $MOUNTLOG/$datum.log
}
declare -i skipDir=1
while true
do
oldest=$($FIND -type d -name *RC* -mtime +40 -printf '%T+ %p\n' | sort -r | tail -n $skipDir | head -n 1)
# echo najstarejsi $oldest
dironly=$(echo $oldest | cut -d' ' -f 2-)
deleteDir "$dironly"
# echo $skipDir $dironly
/bin/sleep 1
if [ "$dironly" = "$testna" ]; then
break
else
testna=$(echo $oldest | cut -d' ' -f 2-)
let "skipDir++"
fi;
# echo primerjava $testna
done
Crontab job
0 2 * * * /mnt/local/TempDrive/Software_RC/.cleanOld.sh
Log output
[root@SambaServer softwareRC]# cat 2017-03-11.log
-------- START --------
-------- END --------