在Bash中如何定义和调用一个函数,该函数通过其参数循环遍历一个数组?

huangapple go评论63阅读模式
英文:

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

问题

以下是要翻译的内容:

在尝试定义一个循环遍历数组的函数时,注释显示了我遇到的错误:

#!/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"

在函数定义中使用关键字 local 并不起作用。为什么在定义一个接受数组作为参数的函数时,${1} 不能正常工作,而在定义简单函数(如 echo_fn)时 ${1} 却能正常工作呢?

英文:

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 "" 
}

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?

答案1

得分: 2

看起来您想将值传递给函数,而不是数组。可以通过`$@`数组的元素访问这些值:
```bash
#!/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"

<details>
<summary>英文:</summary>

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:
```bash
#!/bin/bash
echo_array() {
    for fl in &quot;$@&quot; ; do
        echo &quot;$fl&quot;
    done 
}

echo_fn() {
    echo &quot;$1&quot; 
}

to_be_bckd_p=(&quot;lightningd.sqlite3&quot; &quot;emergency.recover&quot;)
prefs=(&quot;aaa&quot; &quot;bbbb&quot;)

echo_array &quot;${to_be_bckd_p[@]}&quot;
echo_array &quot;${prefs[@]}&quot;
echo_fn &quot;Hi&quot;

答案2

得分: 2

以下是翻译好的内容:

假设使用 bash 4.2+,我们可以使用 nameref 来控制数组(例如,访问数组索引):

echo_array() {
  declare -n _arr="$1"                      # nameref

  for ndx in "${!_arr[@]}"                  # 遍历数组的索引
  do
      echo "$ndx : ${_arr[$ndx]}"           # 打印 'index : value'
  done
}

**注意:** `for val in "${_arr[@]}"` 将遍历数组的 *值*

来试一试:

```bash
$ echo_array to_be_bckd_p                   # 传递数组的名称
0 : lightningd.sqlite3
1 : emergency.recover

$ echo_array prefs                          # 传递数组的名称
0 : aaa
1 : bbbb

$ declare -A assoc=( [a]=1 [b]=2 [c]=3 )    # 添加一个关联数组到混合中

$ echo_array assoc                          # 传递数组的名称
a : 1
b : 2
c : 3
英文:

Assuming bash 4.2+, we can use a nameref to provide control of the array (eg, accessing array indices):

echo_array() {
  declare -n _arr=&quot;$1&quot;                      # nameref

  for ndx in &quot;${!_arr[@]}&quot;                  # loop through array&#39;s indices
  do
      echo &quot;$ndx : ${_arr[$ndx]}&quot;           # print &#39;index : value&#39;
  done
}

NOTE: for val in &quot;${_arr[@]}&quot; will loop through the array's values

Take for a test drive:

$ echo_array to_be_bckd_p                   # pass the name of the array
0 : lightningd.sqlite3
1 : emergency.recover

$ echo_array prefs                          # pass the name of the array
0 : aaa
1 : bbbb

$ declare -A assoc=( [a]=1 [b]=2 [c]=3 )    # add an associative array to the mix

$ echo_array assoc                          # pass the name of the array
a : 1
b : 2
c : 3

huangapple
  • 本文由 发表于 2023年6月13日 04:29:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76460125.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定