how do I run a cron job with a specific user?

9,337

That su is why it fails, that launches an interactive shell. Why not add it to the crontab of the cpc user instead? crontab -e -u cpc

Share:
9,337
gtludwig
Author by

gtludwig

Updated on September 18, 2022

Comments

  • gtludwig
    gtludwig almost 2 years

    My cron and scripting skills are very poor, but I need to run a job every 5 minutes by user 'cpc'. So I created a script and left it at /root.

    My crontab -e entry about it is:

    0-59/5 * * * * /root/bi-kettle.sh

    And this script (bi-kettle.sh) is:

    #!/bin/bash
    su cpc
    cd /home/cpc/data-integration 
    /bin/bash kitchen.sh -rep="01" -job="MainLoad" -user="admin" -pass="admin" -level="Basic"`
    

    But it is not called or run at any moment. What am I missing here?

    Thanks in advance!

    • jippie
      jippie over 11 years
      You definitely want to check a question I asked about an hour ago. It has an answer by Stephane Chazelas that explains how you can create an interactive shell that is identical to the environment your cron job will see. If you walk through his little procedure, you get a prompt and you can test your script step by step and see where it fails. unix.stackexchange.com/a/56503/16841 The only gotcha is that the first command after the procedure has to be /bin/bash, without the she-bang #!.
  • gtludwig
    gtludwig over 11 years
    yes, its permissions are 755. AFAIK it should be enough.
  • gtludwig
    gtludwig over 11 years
    and put the bi-kettle.sh script under /home/cpc?
  • Dennis Kaarsemaker
    Dennis Kaarsemaker over 11 years
    I would not even use bi-kettle.sh but make this the crontab line: */5 * * * * cd /home/cpc/data-integration && /bin/bash kitchen.sh -rep="01" -job="MainLoad" -user="admin" -pass="admin" -level="Basic"`
  • gtludwig
    gtludwig over 11 years
    following your suggestion, I left the cpc user's crontab like this: */5 * * * * cd /home/cpc/data-integration && /bin/bash kitchen.sh -rep="01" -job="MainLoad" -user="admin" -pass="admin" -level="Basic" > /dev/null 2>&1
  • gtludwig
    gtludwig over 11 years
    no luck still... now trying without > /dev/null 2>&1
  • Dennis Kaarsemaker
    Dennis Kaarsemaker over 11 years
    try >> /tmp/my_cronjob.log 2>&1
  • Dennis Kaarsemaker
    Dennis Kaarsemaker over 11 years
    And /check /var/log/cron (or wherever cron logs are stored) to see if the job is run or not.