【问题标题】:Is it possible to perform array assignment before a command in bash?是否可以在 bash 中的命令之前执行数组分配?
【发布时间】:2018-01-12 23:46:47
【问题描述】:

我正在尝试将数组传递给 shell 脚本,如 this question 中所述。我写了一个小脚本,它只是用来接收数组的名称并打印出数组:

#!/bin/bash
echo "$1"
echo "${!1}"
arrayVar=("${!1}")
echo "${arrayVar[1]}"

我在运行脚本时声明了一个数组变量,如下所示:

array=(foo bar test) ./test.sh array[@]

输出:

|array[@]         # the bars are only here to force the final blank line
|(foo bar test)
|

似乎array,实际上不是一个数组,而是简单的字符串(foo bar test)

即使我将脚本修改为直接按名称而不是通过位置参数间接回显array,我也会得到相同的结果。

#!/bin/bash
echo "$1"
arrayVar=("${!1}")
echo $arrayVar
echo "${arrayVar[1]}"

echo $array
echo "${array[1]}"

输出:

|array[@]         # the bars are only here to force the final blank line
|(foo bar test)
|
|(foo bar test)
|

我只是做错了什么,还是 bash 不支持在命令之前分配数组?

【问题讨论】:

    标签: arrays bash


    【解决方案1】:

    目前,bash 不支持导出数组。这记录在man bash:

    数组变量可能(尚未)被导出。

    【讨论】:

      【解决方案2】:

      似乎不支持它。

      如果array=(foo bar test) ./test.sh 不这样做(array 被导出为文字字符串'(foo bar test)',那么

      array=(foo bar test); export array; ./test.sh
      

      应该而且确实,在导出之后,bash 将数组报告为导出的数组(x 表示已导出):

      $ declare -p array
      declare -ax array='([0]="foo" [1]="bar" [2]="test")'
      

      但事实证明这是一个谎言:

      $ env | grep array; echo status=$?
        status=1
      

      【讨论】:

        猜你喜欢
        • 2012-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-20
        相关资源
        最近更新 更多