Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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).

share|improve this question
up vote 2 down vote accepted

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
share|improve this answer
Always put double quotes around parameter substitutions, otherwise the shell will split them into words. (Yeah, I know, now you don't even imagine putting special characters there, but tomorrow you'll put a space in a file name and wonder why your scripts break, or you'll do this in a CGI script and wonder why your website was cracked.) – Gilles Dec 7 '10 at 23:48
You can use a case statement to avoid a long sequence of if and elif if you're going to have more than just a few options. – Dennis Williamson Dec 8 '10 at 0:51

Another form for is the case statement

case "$1" in
    ./ arg1 arg2
    ./ arg3 arg4
    echo "unknown argument: $1"

case uses glob-style matching, so the * means "everything else"

You'll find that bash is a pretty finicky language, where quoting or not quoting a variable can cause big differences in how your script runs. Get into the habit of quoting all your variables.

share|improve this answer

You can also use getopts for a more flexible way of passing arguments to bash script. By using getopts you can remove the fixed ordering associated with the arguments you are passing, which has the risk of passing wrong data if you forget the order of argument.

share|improve this answer
Passing arguments works jus the same, you simply change how you receive/process them. – Daniel Beck Jul 2 '11 at 14:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .