Passing a command with arguments to a script

The best way to handle this is to pass the actual command args to your wrapper as args instead of as a string. You can call your wrapper like this:

my_wrapper "task_name" command arg1 arg2 arg3

my_wrapper would contain the following:

task_name=$1
shift # remove the task_name from the command+args
"$@" # execute the command with args, while preserving spaces etc

You have two choices: you can pass a program to execute with some arguments, or you can pass a shell script. Both concepts can be called “a command”.

A program with some arguments takes the form of a list of strings, the first of which is the path to an executable file (or a name not containing any slash, to be looked up in the list of directories indicated by the PATH environment variable). This has the advantage that the user can pass arguments to that command without worrying about quoting; the user can invoke a shell explicitly (sh -c … if they want). If you choose this, pass each string (the program and its argument) as a separate argument to your script. These would typically be the last arguments to your script (if you want to be able to pass more arguments, you need to designate a special string as an end-of-program-arguments marker, which you then can't pass to the program unless you make the syntax even more complicated).

0 11 * * * my_wrapper.sh "task_name" command arg1 arg2 arg3 ...

and in your script:

#!/bin/zsh
task_name=$1
shift
"$@"

A shell script is a string that you pass to the sh program for execution. This allows the user to write any shell snippet without having to explicitly invoke a shell, and is simpler to parse since it's a single string, hence a single argument to your program. In an sh script, you could call eval, but don't do this in zsh, because users wouldn't expect to have to write zsh syntax which is a little different from sh syntax.

0 11 * * * my_wrapper.sh "task_name" "command arg1 arg2 arg3 ..."

and in your script:

#!/bin/zsh
task_name=$1
sh -c "$2"

Tags:

Shell

Zsh