4

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"
codec
  • 7,978
  • 26
  • 71
  • 127

2 Answers2

4

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.

Community
  • 1
  • 1
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
4

You pass the parameters just as you would do in the Shell.

A good way of testing it is by creating a simple /home/script.sh like:

#!/bin/bash

echo "My first input is $1"
echo "And my second input is $2"

And so on ...

Then run it like so it executes every minute:

* * * * * /home/script.sh arg1 arg2 >> /home/cron_output.log

Use this procedure to make sure your own script is running as desired. In my experience, everything before the >> is assumed as parameter for to the script.

Keep in mind that cronjob runs on its own detached shell, so you need to redirect STDOUT to a file to actually see it working.

RicHincapie
  • 3,275
  • 1
  • 18
  • 30