【问题标题】:Passing An Array From One Bash Script to Another将数组从一个 Bash 脚本传递到另一个
【发布时间】:2013-04-07 19:34:52
【问题描述】:

我是编写 Shell 脚本的新手,遇到了一些困难。

我想要实现的目标

我在scriptOne.sh 中有一个字符串数组,我想将其传递给scriptTwo.sh

到目前为止我做了什么

我可以使用./scriptTwo.sh 从第一个脚本内部执行第二个脚本,并且我已经使用./scriptTwo.sh $variableOne 将字符串变量从一个传递到另一个。

问题是当我尝试传递一个数组变量时它没有被传递。我已经设法让它使用./scriptTwo.sh "${array[@]}" 传递数组的第一个条目,但这只是其中一个条目,我需要所有这些条目。

提前感谢您的帮助

【问题讨论】:

标签: arrays bash shell parameter-passing


【解决方案1】:

你传递数组的方式是正确的

./scriptTwo.sh "${array[@]}"

问题可能在于您接收它的方式。在scriptTwo.sh 中,使用

array=("$@")

【讨论】:

  • 如果我将多个数组传递给第二个脚本会怎样?有没有办法声明哪一个,即arrayOne=("$1@")
  • @DiscoS2:传递多个数组的问题要大得多。不过,可以在每个数组之前添加数组大小,然后在第二个脚本中填充数组。
  • 感谢您的回复。我决定改变我将数据从一个脚本传递到另一个脚本的方式,因为它使长期错误更容易,但感谢您的回答。这绝对有帮助!
【解决方案2】:

我认为如果您使用声明命令,我们可以直接从 sriptOne.sh 读取数组内容。

我在 scriptOne.sh 中声明了一个名为 wes_batch_array 的关联数组,我想将它传递给 scriptTwo.sh 所以我将下面的命令放在 scriptTwo.sh 中:

declare -A wes_batch_array=$(awk -F '=' '{if ($1 ~ /^declare -A wes_batch_array/) {for (i=2;i<NF;i++) {printf $i"=";} printf $NF"\n";}}' < scriptOne.sh)

我已经测试过这个命令,它工作正常。

如果不使用 declare 命令。您可以将数组的内容回显到另一个中间临时文件,并使用上面的 awk 命令来获取 bash 数组的内容。

【讨论】:

    【解决方案3】:

    我解决这个问题的方法是遍历 script1.sh 中的数组,然后使用 for 循环将数组元素传递给 script2.sh。在我的例子中,我将许多元素数量不同的数组传递给不同服务器上的同一个 script2.sh。

    例如:

    script1.sh:

    records="111111111 222222222 333333333"
    myRecordsArray=($records)
    
    for (( i=0 ; i < $(#myRecordsArray[@]} ; i++ )); do
    
    ./script2.sh ${myRecordsArray[i]}
    
    done
    

    script2.sh:

    main () {
    <some code here>
    }
    
    myRecord=$1
    main $myRecord
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多