4

How do I use the positional parameters (which are given from the command line) inside of a function declaration?

When inside the function definition, $1 and $2 are the only the positional parameters of the function itself, not the global positional parameters!

3 Answers3

7

The positional parameters of the caller's scope are not available in a function. You'd need the caller to pass them to the function one way or another.

In bash, that could be done with an array (but beware that arrays other than "$@" in bash start at indice 0 instead of 1 (like in ksh, but contrary to all other shells)).

f() {
  printf 'Caller $1: %s\n' "${caller_argv[0]}"
  printf '    My $1: %s\n' "$1"
}
caller_argv=("$@")
f blah

Or pass them in addition:

f() {
  printf 'Caller $1: %s\n' "$2"
  shift "$(($1 + 1))"
  printf 'My $1: %s\n' "$1"
}

f "$#" "$@" blah

Here with $1 containing the number of positional arguments of the caller, so f knows where its own args start.

0

With bash, you can use the shell variable BASH_ARGV

shopt -s extdebug
# create the array BASH_ARGV with the parameter of the script
shopt -u extdebug
# No more need of extdebug but BASH_ARGV is created

f() {
  printf 'Caller $1: %s\n' ${BASH_ARGV[$((${#BASH_ARGV[*]}-1))]}
  printf '    My $1: %s\n' "$1"
}
f blah
ctac_
  • 1,960
-1

It's not exactly clear to me what you are asking, but the following example might clear things up:

$ cat script
#!/usr/bin/env bash

echo "Global 1st: ${1}"
echo "Global 2nd: ${2}"

f(){
    echo "In f() 1st: ${1}"
    echo "In f() 2nd: ${2}"
}

f "${1}" "${2}"

$ ./script foo bar
Global 1st: foo
Global 2nd: bar
In f() 1st: foo
In f() 2nd: bar
pfnuesel
  • 5,837