0

When we pass an array to a function in bash scripting, how we can access to elements? for example I have this code:

check_corrects() {
    local inp=$1[@]
    echo # i want to echo inp[0]
}
a=(1 2 3)
check_corrects a 

how i can echo inp[0] ?

Vahid Kharazi
  • 5,723
  • 17
  • 60
  • 103
  • `check_corrects a` is not passing the array or any part of it to `check_corrects`. It is passing a single 1-character string "a"... – twalberg Mar 06 '14 at 21:34

3 Answers3

3

You can't pass an array as arguments to a shell function. Arguments are simply numbered parameters. You can cause an array to become these parameters:

testa() { echo "$#"; }
a=(1 2 3)
testa "${a[@]}"
3

but testa $a would echo 1 because it would only pass the first element of 'a' to testa.

But that means, serendipidously, in your case, if you just echo the array expansion directly you'd get the first parameter, which is what you want.

echo "$1"
kojiro
  • 74,557
  • 19
  • 143
  • 201
1

Warning: extreme ugliness ahead. Not for the faint of heart:

check_corrects() {
    local arrayref="$1[@]"
    local array=("${!arrayref}")   # gulp, indirect variable
    local idx=$2
    echo "${array[$idx]}"
}

Now, let's test

a=( 1 2 "foo bar" 3)
check_corrects a 2      # ==> "foo bar"

Phew.

Does not work with associative array: "${ary[@]}" only returns the values, not the keys. Also, won't work with numeric arrays where the keys are non-consecutive.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
1

Just to expound on kojiro's answer, which is quite correct...

What I frequently do when I want to pass an entire array is this:

foo() {
  local a=( "$@" )
  ...
}

a=(1 2 3)
foo "${a[@]}"

This basically reconstructs the values back into an array inside foo(). Note that the quotes are crucial if there's any possibility that the values of individual array elements will contain spaces. For example:

foo() {
  local a=( "$@" )
  echo "foo: Number of elements in a: ${#a[@]}"
}

bar() {
  local a=( $@ ) # wrong
  echo "bar: Number of elements in a: ${#a[@]}"
}

a=(1 2 3 4)
foo "${a[@]}"  # Reports 4 elements, as expected
bar "${a[@]}"  # Also reports 4 elements, so where's the problem?

a=("1 2" 3 "4 5 6")
foo "${a[@]}"  # Reports 3 elements, as expected
bar "${a[@]}"  # Reports 6 elements. Oops!

Edit: Although my example doesn't show it, the quotes on the calling side are also important. That is, if you do foo ${a[@]}, you get the same problem as bar has in the example above. Bottom line is if your array elements are going to contain spaces, you need to use quotes. For a more detailed explanation, see What is the difference between $@ and $* in shell scripts?

Community
  • 1
  • 1
Mike Holt
  • 4,452
  • 1
  • 17
  • 24