I am trying to create a simple resource logging script on Linux Mint 20.3. The script minute_log.sh is expected to analyze the home directory size and log it into a file every minute. Assume USER=itsme.
#!/bin/bash
TARGET_PATH="/home/${USER}"
LOG_PATH="${TARGET_PATH}/log"
DATE_OUT=$(date +%Y%m%d%H%M%S)
LOGFILE="${LOG_PATH}/metrics_${DATE_OUT}.log"
du -sh $TARGET_PATH > $LOGFILE
I run the script normally and works as expected, giving the output 14G /home/itsme in the specified $LOGFILE. Then, I move it to ~/.local/bin and I set up my crontab as follows using crontab -e:
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
SHELL=/usr/bin/bash
* * * * * /home/itsme/.local/bin/minute_log.sh
Using this setup, I noticed that there are no files logged into $LOGFILE. Upon checking the cron service log using systemctl (the command is systemctl status cron.service), I noticed that it tried to run the following:
CGroup: /system.slice/cron.service
├─ 663 /usr/sbin/cron -f
├─128975 /usr/sbin/CRON -f
├─128976 /bin/bash /home/itsme/.local/bin/minute_log.sh
├─128982 /bin/bash /home/itsme/.local/bin/minute_log.sh
└─128983 du -sh /home/
Notice that $USER is considered empty when passed to du command. Then when it tries to log to /home//log/, it failed because of permission restrictions and the folder does not exist there and cannot be created. Hence, the expected log path of /home/itsme/log/ never populated.
However, if I change $TARGET_PATH to the following:
TARGET_PATH="$HOME"
It works without problem and successfully logs the file to to $LOGFILE.
Can anyone explain why this might happen on the cron side?
crongets a very limited repertoire of environment variables. Is there a reason you are not using$HOME, or simply a relative file path?cronjobs will always start in the owner's home directory.$TARGET_PATHto be modifiable to point at arbitrary path. Also, I haven't thought of using "relative to home" path incron. Probably I will try that.croninvocation redrect it to a convenient location.