There is a small python script, with shabang in the beginning.

#!/usr/bin/env python3 

The script runs perfectly through bash, but such lines do not work in crontab -e

 * * * * * /home/user/script/script.py > /home/user/script/log * * * * * python3 /home/user/script/script.py > /home/user/script/log * * * * * /usr/bin/python /home/user/script/script.py > /home/user/script/log 

In addition, nothing appears in the log. syslog reports on command execution:

Apr 10 10:58:01 boss-K55DR CRON [4098]: (user) CMD (python3 /home/boss/.backgrounds/bg_changer.py> /home/boss/.backgrounds/bg)

How to force cron to execute a script?

  • aside: 1- stderr should be redirected to see errors in the log file. Add 2>&1 at the end. 2- Installed scripts should use a fixed address in shebang, for example: /usr/bin/python3 . See Should I put #! (shebang) in Python scripts - jfs
  • @jfs Add 2>&1 at the end of what? What does this sequence do? More precisely, what does &1 mean? - aryndin
  • > /.../log 2>&1 is the redirection syntax. 1, 2 are file descriptors for stdout, stderr streams respectively (by the way, the shell in cron can also be different if you did not explicitly specify SHELL=/bin/bash . In bash it is easier to redirect both streams to one file: /.../script &> /.../file - jfs
  • @jfs I just always thought that 2>1 enough, an ampersand is needed to get the address of the object, by analogy with C? - aryndin
  • If it is interesting how and why 2>1 from 2>&1 in the shell are different, then ask a separate question — this is useful for others (or see an existing question). - jfs

1 answer 1

The solution was found on the English stackoverflow. The problem is that only a limited set of environment variables is available to cron, and to execute a bash script (in my case, the gsetting daemon served as a stumbling block, it was the script that should have addressed it) that requires the DBUS_SESSION_BUS_ADDRESS environment variable:

 PID=$(pgrep gnome-session) export DBUS_SESSION_BUS_ADDRESS=$(grep -z DBUS_SESSION_BUS_ADDRESS /proc/$PID/environ|cut -d= -f2-) 

More details:

[1] https://askubuntu.com/questions/140305/cron-not-able-to-succesfully-change-background

[2] https://stackoverflow.com/questions/10374520/gsettings-with-cron