当从我的 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
该脚本旨在删除最旧的目录,其名称类似于其中之一:
CS20210730_1341
CS20210730_2350
CS20210731_2350
这项工作每天完成一次,因为CS202*
rsync 每天都会创建一个新的备份来进行备份。放置在脚本中的行echo
只是为了调试。代码需要不是 sudo
删除指定的目录。它无法从cron
我的用户的 crontab 中工作jerzy
。当从同一用户的 shell 执行时,它会完成这项工作,为什么会这样呢?
我的 cron 中的环境变量:
PATH=/usr/bin:/bin:/usr/sbin:/sbin:/home/jerzy/.cargo/bin
SHELL=/bin/bash
到目前为止我已经诊断出:
rm
确实可以从 cron 工作,就像/usr/bin/rm -r /home/jerzy//pCloudDrive/CS20210730_1341
编写脚本时删除目标一样。这不是权限的问题。- 正如文件的创建所证明的那样,脚本的执行确实开始了
/home/jerzy/to.be.removed
。
为什么这个脚本不能在 cron 中运行?