Is there a way to get the positional parameters of the script from inside a function in bash?
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.
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