このスクリプトがcronでは機能しませんが、シェルから呼び出すと機能するのはなぜですか?

このスクリプトがcronでは機能しませんが、シェルから呼び出すと機能するのはなぜですか?

私のシェルから呼び出すと、次のコードが機能します。

#!/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はバックアップ用に毎日新しいバックアップを作成するため、これは1日1回実行されます。スクリプトに配置された行はデバッグecho用です。コード要求いいえ sudo指定されたディレクトリを削除します。cron私のユーザーのcrontab内では動作しませんjerzy。同じユーザーのシェルで実行すると、操作が実行されます。なぜですか?

私のcronの環境変数:

PATH=/usr/bin:/bin:/usr/sbin:/sbin:/home/jerzy/.cargo/bin

SHELL=/bin/bash

これまで、私は次のように診断しました。

  • rm/usr/bin/rm -r /home/jerzy//pCloudDrive/CS20210730_1341スクリプト中にターゲットを削除するかのようにcronで動作します。これは権限の問題ではありません。
  • ファイルの生成が示すように、スクリプトの実行が開始されます/home/jerzy/to.be.removed

このスクリプトがcronで実行されないのはなぜですか?

ベストアンサー1

おすすめ記事