I am trying to write a shell script that receives as an input a command with arguments and runs it.
As an example, I am hoping to use this in cron
as follows:
0 11 * * * my_wrapper.sh "task_name" "command arg1 arg2 arg3 ..."
The details of what my_wrapper.sh
does don't matter, but it is a zsh
script and I want it to receive command arg1 arg2 arg3 ...
and invoke it. Note that the arguments may contain single quotes, double quotes, etc.
What is the proper way of passing and receiving commands with arguments to scripts?
Update:
On the command line in zsh, @Gilles' first solution works great:
#!/bin/zsh
task_name=$1
shift
"$@" > /path/to/logging_directory/$task_name
and then invoking > my_wrapper.sh date "%Y-%b-%d"
from the command line does the job.
However, when I try to use it as follows in cron
:
CRON_WRAPPER="/long/path/to/my_wrapper.sh"
0 11 * * * $CRON_WRAPPER "current_date.log" date "+%Y-%b-%d"
It doesn't work.
Final update (problem solved):
As explained in Gilles' answer, crontab
requires escaping any %
signs. After changing the above to:
CRON_WRAPPER="/long/path/to/my_wrapper.sh"
0 11 * * * $CRON_WRAPPER "current_date.log" date "+\%Y-\%b-\%d"
it worked. All set.
my_wrapper.sh
is meant to be a generic wrapper for cron jobs. For now it only logs the output on a predefined folder (the folder's name is given by the current date, and the logging filename istask_name
followed by the current timestamp). I also hope to email myself a note saying that the tasktask_name
finished correctly. Are you suggesting to not use a generic wrapper to do all this? – Amelio Vazquez-Reina Dec 28 '14 at 19:29