0

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?

4
  • cron gets a very limited repertoire of environment variables. Is there a reason you are not using $HOME, or simply a relative file path? cron jobs will always start in the owner's home directory. Commented Feb 26, 2022 at 10:33
  • @tripleee I would like $TARGET_PATH to be modifiable to point at arbitrary path. Also, I haven't thought of using "relative to home" path in cron. Probably I will try that. Commented Feb 26, 2022 at 11:03
  • Probably a better design altogether is to pass the destination file as a command-line argument, or simply have the script print to standard error and have the cron invocation redrect it to a convenient location. Commented Feb 26, 2022 at 11:06
  • @tripleee The problem is that the destination/output file name changes every minute and I want to put them all in a directory. But if you mean the destination directory as an argument, then that might work. Commented Feb 26, 2022 at 11:32

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.