9

The following variables are used to get the positional parameters:

$1, $2, $3, etc.
$@
$#

But they are used for both positional parameters of the script and the positional parameters of a function.

When I use these variables inside a function, they give me the positional parameters of the function.

Is there a way to get the positional parameters of the script from inside a function?

4 Answers 4

13

No, not directly, since the function parameters mask them. But in Bash or ksh, you could just assign the script's arguments to a separate array, and use that.

#!/bin/bash
ARGV=("$@")
foo() {
     echo "number of args: ${#ARGV[@]}"
     echo "second arg: ${ARGV[1]}"
}
foo x y z 

Note that the numbering for the array starts at zero, so $1 goes to ${ARGV[0]} etc.

2
  • 1
    Note that if you need the arguments including $0 or with a number that match the numbering of positional arguments, use: ARGV=( "$0" "$@" ).
    – user232326
    Oct 3, 2019 at 15:23
  • For ease of numbering, consider : % set a b c; echo ${@:0} gives: zsh a b c
    – Tom Hale
    Jun 30 at 15:08
7

Another way to get the param of the script with bash is to use the Shell Variables BASH_ARGC and BASH_ARGV

#!/bin/bash
shopt -s extdebug
test(){
  echo 'number of element in the current bash execution call stack = '"${#BASH_ARGC[*]}"
  echo 'the script come with '"${BASH_ARGC[$((${#BASH_ARGC[*]}-1))]}"' parameter(s)'
  echo 'the first is '"${BASH_ARGV[$((${#BASH_ARGV[*]}-1))]}"
  echo 'there is 2 way to get the parameters of this function'
  echo 'the first is to get $1,...,$n'
  echo '$1 = '"$1"
  echo '$2 = '"$2"
  echo 'the second with the use of BASH_ARGC and BASH_ARGV'
  echo 'this function '"${FUNCNAME[0]}"' come with '"${BASH_ARGC[0]}"' parameter(s)'
  echo 'the second is '"${BASH_ARGV[0]}"
  echo 'the first is '"${BASH_ARGV[1]}"
}
essai(){
  test paramtest1 "$3"
}
essai paramessai1 paramessai2 paramessai3
1

As a POSIX portable solution, sometimes, it might be viable to just add the original "$@" to the function arguments and shift the parameters inside the function:

#!/bin/sh
foo () {
  printf '%s-' "$@"
  printf '\n'
  # Save function parameters to custom variables
  x="$1"
  y="$2"
  z="$3"
  shift 3
  # At this point, "$@" regained its original value
  printf '%s-' "$x" "$y" "$z" "$@"
  printf '\n'
}
foo 1 2 3 "$@"

Example call:

$ sh example.sh 4 5 6
1-2-3-4-5-6-
1-2-3-4-5-6-
-2

Using shift command in shell, you can access all positional parameters as shown below. The params get shifted left and take first position.

while (( "$#" ))
do
  echo $1
  shift
done

You must log in to answer this question.

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