Reputation: 720
I need to pass an array as an argument to a function (that is fine) and then get its length (I don't get that to work).
Working example:
function foo {
declare -a idn=("${!1}")
echo "idn=${idn[@]}"
n=${#idn[@]}
echo "n=$n"
}
identifier=(a b c d e)
echo "len is ${#identifier[*]}"
echo foo
foo identifier[*]
The output of that is:
len is 5 #that is OK
foo
idn=a b c d e
n=1 #should be 5
Length outside function is ok, but it is not inside the function.
I am using GNU bash, version 4.3.42(1)-release (x86_64-suse-linux-gnu)
Upvotes: 1
Views: 114
Reputation: 26592
Your original script should work by just changing last line to :
foo "identifier[@]"
Upvotes: 2
Reputation: 4688
If you want to pass the individual arguments of the array a
, b
, c
, d
, e
to your function, use foo "${identifier[@]}"
. Then in the function you can use $#
to get the number of arguments.
Or if you want to pass the name of the variable to your function, you could use a local nameref
variable idn
which
is a reference to the identifier
array.
foo() {
echo "n=$#"
}
foo2() {
local -n idn=$1
echo "n=${#idn[@]}"
}
identifier=(a b c d e)
echo "len is ${#identifier[*]}"
foo "${identifier[@]}"
foo2 identifier
Output:
len is 5
n=5
n=5
Upvotes: 0
Reputation: 19555
Either use a -nameref variable like this:
#!/usr/bin/env bash
foo ()
{
# If argument 1 is not an array, return an error
[ "${!1@a}" = 'a' ] || return 2
# Make idn a nameref variable referrencing the array name from argument 1
declare -n idn="$1"
echo 'idn:' "${idn[@]}"
n=${#idn[@]}
echo 'n:' "$n"
}
identifier=(a b c d e)
echo "len is ${#identifier[*]}"
echo foo
foo identifier
Or pass array elements as value:
#!/usr/bin/env bash
foo ()
{
declare -a idn=("${@}")
echo 'idn:' "${idn[@]}"
n=${#idn[@]}
echo 'n:' "$n"
}
identifier=(a b c d e)
echo "len is ${#identifier[*]}"
echo foo
foo "${identifier[@]}"
Upvotes: 2