arrays - 如何将数组参数传递给 Bash 脚本

标签 arrays bash arguments

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

test.sh argument1 array argument2

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

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

最佳答案

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

关于arrays - 如何将数组参数传递给 Bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17232526/

相关文章:

bash - cygwin bash 在 emacs shell 中无法正确显示

bash - Rsync 删除参数未删除

linux - 使用 sed 有条件地匹配一个词

r - 如何访问函数参数的默认值?

python - 在 Python 中通过三元运算符传递函数参数

c - 从命令行将参数传递给 C 程序

python - 使用 numpy unique 计数时避免使用 python for 循环来提高性能

javascript - React Reconciliation 是这样工作的吗?

Javascript 数组数组 -> array[index] 未定义

c++ - unsigned int 转换为 char 数组。 itoa 的替代品?