Run a script with arguments using crontab

12,233

Solution 1

Try creating a simple wrapper script called /opt/start-service.sh with this content:

#!/bin/sh
/opt/service.sh start

and make sure it's executable then use

* * * * * /opt/start-service.sh

as the crontab entry

Solution 2

I was having this same issue where I using the following crontab:

0 23 * * * sudo -u myname /home/myname/bin/buildme.sh -f >> /home/myname/log.txt

And inside the bash script I was using this to get the -f option:

while getopts ":f" opt; do
    case $opt in
        f)
            force_full=1
            ;;
        \?)
            echo "Invalid option: -$OPTARG" >&2
            ;;
    esac
done

So I noticed that the option wasn't being honored when I ran this through cron for some reason. Well, adding /bin/bash to the cronjob fixed it right up. The new crontab is:

0 23 * * * sudo -u myname /bin/bash /home/myname/bin/buildme.sh -f >> /home/myname/log.txt

Hope it helps!

Share:
12,233
Rg90
Author by

Rg90

"Well, it works in the development environment!"

Updated on June 22, 2022

Comments

  • Rg90
    Rg90 almost 2 years

    I know this may have been answered earlier in various posts, but I've not been able to make this run myself.

    I have a bash script (service.sh) that I would like to run every minute. It needs an argument to be passed (start in this case).

    Using another script (test.sh) I am scheduling the cron expression for the above script:

    echo "* * * * * /opt/service.sh start" > /opt/cronForSecops
    crontab /opt/cronForSecops
    

    I can see by using crontab -l that this is being set correctly as:

    * * * * * /opt/service.sh start
    

    However, the service.sh does not run, and I see no logs/files being created (which the service.sh file is supposed to do, when I run it normally).

    Can anybody please guide me on where I am going wrong?