What is wrong in this approach I can't get correct value of array length
#!/bin/bash
foo(){
val=$@
len=${#val[@]}
echo "Array contains: " $val
echo "Array length is: " $len
}
var=(1 2 3)
foo ${var[@]}
Output:
Array contains: 1 2 3
Array length is: 1
Change val=$@ to val=("${@}") and you should be fine.
This answer in unix.stackexchange explains why:
You're flattening the input into a single value.
You should do
list=("${@}")to maintain the array and the potential of whitespace in arguments.
If you miss out the " then something like
./script.sh "a b" 2 3 4will return a length of 5 because the first argument will be split up
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With