如何将数组参数传递给Bash脚本 [英] How to pass an array argument to the Bash script
本文介绍了如何将数组参数传递给Bash脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我惊讶的是,在搜索1小时后我没有找到答案. 我想像这样将数组传递给我的脚本:
It is surprising me that I do not find the answer after 1 hour search for this. I would like to pass an array to my script like this:
test.sh argument1 array argument2
我不想将其放在另一个bash脚本中,如下所示:
I DO NOT want to put this in another bash script like following:
array=(a b c)
for i in "${array[@]}"
do
test.sh argument1 $i argument2
done
推荐答案
Bash数组不是一流的值"-您不能像一个事物"那样传递它们.
Bash arrays are not "first class values" -- you can't pass them around like one "thing".
假设test.sh
是一个bash脚本,我会做
Assuming test.sh
is a bash script, I would do
#!/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
这篇关于如何将数组参数传递给Bash脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文