填写阵列在bash函数参数传递 [英] Fill array passed as argument in bash function

查看:111
本文介绍了填写阵列在bash函数参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要填写一个函数里的数组,将它作为一个参数,并且不使用全局变量(函数将在这里和那里叫不同的阵列)。

I need to fill an array inside a function, passing it as an argument and NOT using a global variable (the function will be called here and there with different arrays).

我读过这个讨论<一个href=\"http://stackoverflow.com/questions/16461656/bash-how-to-pass-array-as-an-argument-to-a-function\">bash如何通过数组作为​​参数传递给函数以及所使用的密码按姓名的解决方案,几乎做到。

I've read this discussion bash how to pass array as an argument to a function and used the pass-by-name solution, that ALMOST do the trick.

下面是我的code

#!/bin/bash

function fillArray {
  arrayName=$1[@]
  array=("${!arrayName}")
  for i in 0 1 2 3
  do
    array+=("new item $i")
  done

  echo "Tot items in function: ${#array[@]}"
  for item in "${array[@]}"
  do
    echo $item
  done
  echo
}

myArray=("my item 0" "my item 1")

fillArray myArray

echo "Tot items in main: ${#myArray[@]}"
for item in "${myArray[@]}"
do
  echo $item
done

下面是输出

Tot items in function: 6
my item 0
my item 1
new item 0
new item 1
new item 2
new item 3

Tot items in main: 2
my item 0
my item 1

所以,函数正确地使用作为参数传递的阵列(前两项是一个在主声明加入),并追加新项目到数组。函数调用后,在主,添加的项都将丢失。

So, the function correctly use the array passed as parameter (first two items are the one added in main declaration), and append the new items to the array. After the function call, in main, the added items are lost.

我在想什么?可能是一些通通过引用/传递通过拷贝的东西...

What am I missing? Probably some pass-by-reference/pass-by-copy things...

谢谢!

推荐答案

在此回答使用这种技术。修改,则可以

In this answer using such technique. Modified, you can

addtoarray () { var="$1"; shift 1; eval "$var+=($(printf "'%s' " "$@"))"; }

arr=('my item 0' 'my item 1')
printf "%s\n" "${arr[@]}"
echo ====
addtoarray arr 'my new item 2' 'my new item 3'
printf "%s\n" "${arr[@]}"

打印

my item 0
my item 1
====
my item 0
my item 1
my new item 2
my new item 3

作品也初始化数组

works also for initializing arrays

addtoarray secarr $(seq 5)
printf "%s\n" "${secarr[@]}"

打印:

1
2
3
4
5

修改

功能分解 - 可以作为code发电机

EDIT

Decomposition of the function - works as code generator

addtoarray () { var="$1"; shift 1; eval "$var+=($(printf "'%s' " "$@"))"; }


  • 函数的第一个参数是可变的名称(!)(而不是值)

  • 存储的名称(适用于 $ 1 ),它变成 $ VAR 和转移它出从参数

  • 现在,参数包含了像 VAL1 val2的阵列
  • 唯一的新元素
  • 现在,构建一个bash命令:

    • the function's 1st argument is the variable name(!!!) (not value)
    • storing the name (in $1) it into $var and shifting it out from the arguments
    • now the arguments contains only new elements for the array like val1 val2
    • now constructing an bash command:
    • somearrayname+=('elemnts1' 'element2' .... )
      


      • 其中 somearrayname 是我们的第一个ARG
      • 通过变量名
      • 的printf'%s'的$ @创建一个从ARG-list中的单引号的数组成员

      • 所以在调用该函数为 addtoarray ARR VAL1间隔val2的我们生成下的字符串
      • 的情况下,

        • where the somearrayname is the variable name what we passed as the 1st arg
        • the printf "'%s '" "$@" creates the single-quoted array members from the arg-list
        • so in case of calling the function as addtoarray arr val1 "spaced val2" we generating the next string
        • arr+=('val1' 'spaced val2' )
          

          这是一个正确的建设,将成员添加到名为改编阵列 - 不管前contets,例如增加了新的元素,它的尽头。 (如果是空的,到底是其开始)

          this is an correct construction to adding members to the array named arr - regardless if before contets, e.g. adds the new elements to its end. (if it was empty, the end is its start)


          • 最后评估 执行上面的生成的字符串

          • 在结果你有一个初始化/修改后的数组 $改编($的ARR是全局变量,因此在功能可见太)

          • finally the eval executes the above generated string
          • in the result you got an initialized/modified array $arr (the $arr is global variable, therefore is visible in the function too)

          最后 - 惨遭偷@ chepner的回答,用他的技术)的 addtoarray SI简单:

          And finally - brutally stole @chepner's answer ;) using his technique the addtoarray si simple as:

          addtoarray () {
              declare -n arrname=$1
              shift 1;
              arrname+=("$@")
          }
          

          如果您有bash的4.3,你应该接受@ chepner的回答 - 这是最好的

          这篇关于填写阵列在bash函数参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆