41

令我惊讶的是,在搜索了 1 小时后我没有找到答案。我想像这样将一个数组传递给我的脚本:

test.sh argument1 array argument2

我不想把它放在另一个 bash 脚本中,如下所示:

array=(a b c)
for i in "${array[@]}"
do
  test.sh argument1 $i argument2
done
4

5 回答 5

37

Bash 数组不是“一流的值”——你不能像一个“东西”一样传递它们。

假设test.sh是一个 bash 脚本,我会做

#!/bin/bash
arg1=$1; shift
array=( "$@" )
last_idx=$(( ${#array[@]} - 1 ))
arg2=${array[$last_idx]}
unset array[$last_idx]

echo "arg1=$arg1"
echo "arg2=$arg2"
echo "array contains:"
printf "%s\n" "${array[@]}"

并像调用它一样

test.sh argument1 "${array[@]}" argument2
于 2013-06-21T10:29:36.570 回答
18

有这样的脚本arrArg.sh

#!/bin/bash

arg1="$1"
arg2=("${!2}")
arg3="$3"
arg4=("${!4}")

echo "arg1=$arg1"
echo "arg2 array=${arg2[@]}"
echo "arg2 #elem=${#arg2[@]}"
echo "arg3=$arg3"
echo "arg4 array=${arg4[@]}"
echo "arg4 #elem=${#arg4[@]}"

现在在 shell 中像这样设置你的数组:

arr=(ab 'x y' 123)
arr2=(a1 'a a' bb cc 'it is one')

并传递这样的参数:

. ./arrArg.sh "foo" "arr[@]" "bar" "arr2[@]"

上面的脚本将打印:

arg1=foo
arg2 array=ab x y 123
arg2 #elem=3
arg3=bar
arg4 array=a1 a a bb cc it is one
arg4 #elem=5

注意:我使用. ./script语法执行脚本可能看起来很奇怪。请注意,这是为了在当前 shell 环境中执行脚本的命令。

:为什么是当前的 shell 环境,为什么不是子 shell?
A.因为 bash 不会将数组变量导出到子进程,正如bash 作者本人在此处记录的那样

于 2013-06-21T10:23:26.670 回答
1

您可以将数组写入文件,然后在脚本中获取文件。例如:

数组.sh

array=(a b c)

测试.sh

source $2
...

运行 test.sh 脚本:

./test.sh argument1 array.sh argument3
于 2018-04-09T06:46:32.017 回答
0

如果值有空格(并且作为一般规则),我会投票支持glenn jackman's answer,但我会通过将数组作为最后一个参数传递来简化它。毕竟,似乎你不能有多个数组参数,除非你做一些复杂的逻辑来检测它们的边界。

所以我会这样做:

ARRAY=("the first" "the second" "the third")
test.sh argument1 argument2 "${ARRAY[@]}"

这与以下内容相同:

test.sh argument1 argument2 "the first" "the second" "the third"

test.sh做:

ARG1="$1"; shift
ARG2="$1"; shift
ARRAY=("$@")

如果值没有空格(即它们是 url、标识符、数字等),这是一个更简单的选择。这样你实际上可以有多个数组参数,并且很容易将它们与普通参数混合:

ARRAY1=(one two three)
ARRAY2=(four five)
test.sh argument1 "${ARRAY1[*]}" argument3 "${ARRAY2[*]}" 

这与以下内容相同:

test.sh argument1 "one two three" argument3 "four five"

test.sh你做:

ARG1="$1"
ARRAY1=($2) # Note we don't use quotes now
ARG3="$3"
ARRAY2=($4)

我希望这有帮助。我写这篇文章是为了帮助(你和我)理解数组是如何工作的,以及如何使用*数组@

于 2021-11-18T14:57:41.290 回答
-4

如果这是您的命令:

test.sh argument1 ${array[*]} argument2

您可以像这样将数组读入 test.sh:

arg1=$1
arg2=${2[*]}
arg3=$3

它会抱怨你(“糟糕的替代”),但会起作用。

于 2017-02-28T17:08:52.000 回答