7

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?

9

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.

  • 1
    Note that if you need the arguments including $0 or with a number that match the numbering of positional arguments, use: ARGV=( "$0" "$@" ). – Isaac Oct 3 '19 at 15:23
5

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.