bashfunctionscope

How do I define and the call a function in Bash that loops through an array given as its parameter?


Comments show what errors I get when trying to define a function that loops through an array,

#!/usr/bin/bash

local to_be_bckd_p=("lightningd.sqlite3" "emergency.recover")
prefs=("aaa" "bbbb")
 
echo_array() {
  
  #for fl in "${1[@]}"; do echo "${fl}";done #${1[@]}: bad substitution
  #for fl in "${*[@]}"; do echo "${fl}";done #${@[@]}: bad substitution
  #for fl in "${@[@]}"; do echo "${fl}";done #${@[@]}: bad substitution
  for fl in "${to_be_bckd_p[@]}"; do echo "${fl}";done 
}

echo_fn() {
  echo "${1}" 
}

echo_array "${to_be_bckd_p[@]}"
echo_array "${prefs[@]}" #This loops through `"${to_be_bckd_p[@]}"`
echo_fn "Hi"

Using the keyword local in the function definition does not help. Why using ${1} doesn't work in defining a function that is meant to take an array as its argument whereas ${1} works fine in the definitions of simpler functions such as echo_fn?


Solution

  • It seems you want to pass the values to the function, not the array. The values can be accessed as the elements of the $@ array:

    #!/bin/bash
    echo_array() {
        for fl in "$@" ; do
            echo "$fl"
        done 
    }
    
    echo_fn() {
        echo "$1" 
    }
    
    to_be_bckd_p=("lightningd.sqlite3" "emergency.recover")
    prefs=("aaa" "bbbb")
    
    echo_array "${to_be_bckd_p[@]}"
    echo_array "${prefs[@]}"
    echo_fn "Hi"