如何将数组传递给bash shell脚本?

时间:2016-04-23 07:34:07

标签: arrays linux bash shell unix

如何将数组作为变量从第一个bash shell脚本传递给第二个脚本。

first.sh
#!/bin/bash
AR=('foo' 'bar' 'baz' 'bat')
sh second.sh "$AR" # foo
sh second.sh "${AR[@]}" # foo
second.sh
#!/bin/bash
ARR=$1
echo ${ARR[@]}

在这两种情况下,结果都是foo。但我想要的结果是foo bar baz bat

我做错了什么以及如何解决?

2 个答案:

答案 0 :(得分:3)

使用

sh second.sh "${AR[@]}"

将数组元素拆分为不同的参数,即

sh second.sh "${A[0]}" "${A[1]}" "${A[2]}" ...

并在second.sh中使用

ARR=("$@")

将命令行参数收集到数组中。

答案 1 :(得分:1)

尝试使用ARR=$1更改second.sh中的ARR=("$@")$1假设一个变量,但您需要序列化所有数组项。