drohhyn
drohhyn

Reputation: 5

Crontab: read argument from file

I am trying to execute a python script (with chmod +x) which accepts several options via cronjob. One option is a password which I don't want to store in the crontab file, so I saved it with chmod 600 in my user's home directory (OS: raspbian). My crobtab line is:

* * * * 5 [ $(date +\%d) -le 07 ] && /opt/scripts/myscript.py -p '$(< /home/pi/mypasswordfile)'  >> /tmp/backup.log 2>&1

The line

/opt/scripts/myscript.py -p '$(< /home/pi/mypasswordfile)'  >> /tmp/backup.log 2>&1

is executed correctly with bash, but not from the crontab. This is correct as crontab does not execute a bash - but how to do it correctly?

Thanks in advance!

Upvotes: 0

Views: 905

Answers (4)

Rafael Aguilar
Rafael Aguilar

Reputation: 3279

You could just capture your password and pass it as an argument using cat & backticks:

/opt/scripts/myscript.py -p `cat /home/pi/mypasswordfile` >> /tmp/backup.log

Disclosure: backticks have been deprecated in favor of $() but sometimes just doesn't fit the scenario.

Upvotes: 1

Jamil Said
Jamil Said

Reputation: 2093

I would try:

bash -c '/opt/scripts/myscript.py -p $(< /home/pi/mypasswordfile)'

Also, sometimes you might need to pass environmental variables, specially DISPLAY for some programs to run correctly, for example:

* * * * 5 env DISPLAY=:0 [ $(date +\%d) -le 07 ] && bash -c '/opt/scripts/myscript.py -p $(< /home/pi/mypasswordfile)'  >> /tmp/backup.log 2>&1

Upvotes: 0

Barmar
Barmar

Reputation: 781350

I generally recommend against putting any complex syntax directly into crontab files. Put it into a script, and run the script from crontab. So create a script like runmyscript.sh that contains:

#!/bin/bash
if [ $(date +%d) -le 7 ] 
then
    /opt/scripts/myscript.py -p "$(< /home/pi/mypasswordfile)"
fi

and change the crontab to:

* * * * 5 /opt/scripts/runmyscript.sh >> /tmp/backup.log 2>&1

Upvotes: 3

chepner
chepner

Reputation: 531480

Simply add

SHELL=/bin/bash

to your crontab file, to use bash instead of /bin/sh to execute the commands.

Upvotes: 1

Related Questions