Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in getting array length in bash after passing to function

Tags:

arrays

bash

shell

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
like image 274
Dsujan Avatar asked Feb 23 '26 18:02

Dsujan


1 Answers

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 4 will return a length of 5 because the first argument will be split up

like image 182
Maroun Avatar answered Feb 25 '26 07:02

Maroun