Linux – Passing parameters to a shell script running as a cronjob


I am new to bash scripting (not programming in general).

I am writing a bash script that will run a Python script I have written.

I want to be able to do the following:

  • Pass parameters to the bash script via the cronjob (so I can have two cron jobs) one to be run with parameter 'foobar', and the other 'foo'

  • switch based on the parameter passed to the bash script (by switching, I mean an if/else based on the paramter passed to the bash script).

Best Answer

I was thinking of referring you to stackoverflow, but this is such low level 'programming' it may be best to just do it here.

The first parameter to a shell script is referenced by $1, the second $2, etc... The tenth can't be called $10 because that's $1 followed by a 0, so you refer to it as ${10}, though if you need to refer to the tenth parameter explicitly (and not handling it in a loop) you're probably doing something wrong.

The count of parameters is in the variable $#

I'd suggest:

if [ $# -ne 1 ]
    echo "No parameter given" >&2
    exit 1
elif [ "$1" == 'foo' ]
    ./script someparams ....
elif [ "$1" == 'foobar' ]
    ./script otherparams ....
    echo "Bad parameter given" >&2
    exit 1
Related Question