tags:

views:

39

answers:

3

Inside a function, $1 ... $n are the parameters passed to that function. Outside a function $1 ... $n are the parameters passed to the script.

Can I somehow access the parameters passed to the script inside a function?

+2  A: 

Usually you just pass them as parameters to the function at call time.

The (uglier) alternative is to put them in global variables.

Jean
+1 Absolutely the right answer.
T.J. Crowder
A: 

You should probably use "$@" and pass that at the end of your function's argument list. Inside the function, shift after parsing your arguments and use $1 to $n as normally.

Benoit
+2  A: 

You can store all of your script arguments in a global array:

args=("$@")

and then access them in a function:

f(){
    echo ${args[0]} ${args[1]}
}
dogbane
I think that `function f(){` is not valid. You should use `f() {` or `function f {` instead.
Benoit
I have corrected my answer, but `function f(){}` did work for me.
dogbane