Search code examples
bashcroncron-task

is there a difference in error output when placing error logging in the script vs in the cronjob itself?


I am trying to figure out why the script runs using ./runmusic but isnt launched from the cronjob. Where and why would be the best place to put the error reporting?

my script

pi@raspberrypi ~/Music $ cat runmusic 
#!/bin/bash    
exec >>omx_log_from_runmusic 2>&1
echo $(date)
DISPLAY=:0 

var=$(\ls songs/|shuf -n 1)
#omxplayer -o local /home/pi/Music/Bloodletting.mp3
omxplayer -o local "/home/pi/Music/songs/$var"

$crontab -l

* * * * * bash /home/pi/Music/runmusic > /tmp/setvals

I am not getting error reports from either of these files right now, although I am getting expected text output from the in-script logging. eg "Have a nice day :)" as the closing of omxplayer


Solution

  • As mentioned in comments, you're already redirecting all the output with exec, so there's nothing for cron to log. Assuming the permissions are reasonable, you should see your logging in omx_log_from_runmusic. You may want to specify an explicit path to the log file and ensure the user running cron has permission to write to it.

    There's no need to create a subshell to run date and then echo the result, just run the command. It will be sent to the log with all the other output.

    You would typically set your script to executable (chmod +x mymusic) and then call it directly from cron, as opposed to calling bash and passing the script name as an argument. Also related to cron, you're calling this every minute; are all your songs less than a minute long? If not, you may want to check to make sure omxplayer isn't still running before starting a new one.

    And, you should not be parsing the output from ls as you will run into problems as soon as you come across a file with whitespace in the name (see also bash FAQ 50.) You can use a glob to get the file list into an array, and then use RANDOM to grab an element out of the array.

    #!/bin/bash
    exec >> /full/path/to/omx_log_from_runmusic 2>&1
    date
    DISPLAY=:0 
    
    if pgrep omxplayer
    then
        exit
    else
        files=(/home/pi/Music/songs/*)
        n=${#files[@]}
        omxplayer -o local "${files[RANDOM % n]}"
    fi