Search code examples
bashcron

How to pass parameters while invoking script in cron?


I want to execute a script with some parameters as a cron job. I have configured the crontab using crontab -e with the following content

*/2 * * * * /root/todo-api/workspace/docker.sh c4e842c79337

but it is not working. When I used

*/2 * * * * /root/todo-api/workspace/docker.sh

it worked. How to pass parameters while invoking a script in cron? Here is my docker.sh script and it works if I directly execute it from shell.

CONTAINER=$1    

RUNNING=$(docker inspect --format="{{.State.Running}}" $CONTAINER 2> /dev/null)

if [ $? -eq 1 ]; then
  echo "UNKNOWN - $CONTAINER does not exist."
  exit 3
fi

if [ "$RUNNING" == "false" ]; then
  echo "CRITICAL - $CONTAINER is not running."
curl -H "Content-type: application/json" -X POST -d '{"routing_key": "3ef61cda125048a390d46cdb8d425590","event_action": "trigger","payload": {"summary": "Docker Container '$CONTAINER' down", "source": "'$CONTAINER'", "severity": "critical" }}' "https://events.pagerduty.com/v2/enqueue"
  exit 2
fi

echo "OK"

Solution

  • The first crontab entry looks correct. Since there is no #! /bin/bash line, you might need to put bash in front of the invocation, e.g.

    */2 * * * * /bin/bash /root/todo-api/workspace/docker.sh c4e842c79337
    

    According to docker inspect

    Usage

    docker inspect [OPTIONS] NAME|ID [NAME|ID...]
    

    the second invocation without $CONTAINER must fail, because inspect expects a name or some id.

    To debug this further, follow this question How to debug a bash script? and keep the output from stderr, e.g. remove 2>/dev/null.