1

I have created a bash script which first activates a python virtual environment, and then runs a python file. When I execute the bash script manually, the python file runs as intended. Bash script code:

sample.sh

#!/usr/bin/env bash

source ./project/bin/activate
python3 /home/abc/project/server/sample.py

However, when I try to run this bash script using cron, the python file does not execute. cron:

16 12 * * * /home/abc/sample.sh > /home/abc/bulkcat.log 2>&1

When this cron triggers at the specified time, the python file inside my bash script does not run and the log file is empty.

What seems to be wrong with my code?

3
  • 2
    try giving full path to python. ex: /usr/bin/python3 /home/abc/project/server/sample.py Commented Mar 15, 2018 at 7:01
  • @Rakesh Giving the full Python path gave me this error: SyntaxError: unknown decode error Commented Mar 15, 2018 at 7:36
  • Looks like the error is from your script Commented Mar 15, 2018 at 7:37

2 Answers 2

1

It might well be the relative path you're using in the source command. Cron will run your script from a different directory, so

source ./project/bin/activate

will likely not be a valid path. Try

source /home/abc/project/bin/activate

... guessed path based on the full path in your python3 ... line.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried giving the absolute path for activating my virtual environment, but this didn't seem to solve my issue.
0

Cron writes logs and you can find the error which occured when it tried to execute the task - an answer to this question mentions usual locations where to look for these logs.

Most common issues are:

  • cron is using sh and not bash ignoring shebang in your script - you can try configuring your cron job like 6 12 * * * /bin/bash /home/abc/sample.sh > /home/abc/bulkcat.log 2>&1
  • the script not having permission to be executable set - this can be fixed by running chmod 700 /home/abc/sample.sh or chmod 755 /home/abc/sample.sh - the latter should be used only if you want to allow other users to read and execute your script
  • as mentioned already in another answer, always use absolute paths in cron job as cron might execute your script from other directory than you expect - I'm also using wrapper bash script in such scenarios - I give absolute path to the script in cron job and the first thing the bash script does is cd /desired/work/directory

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.