繁体   English   中英

如何传递和获取数组作为shell脚本的参数

[英]How to pass and get array as an argument to shell script

我将多个参数传递给shell脚本。 我那个脚本我想创建一个从第二个参数到最后一个参数的数组。 这我可以用下面的 -

arg=$1
shift
while [[ $1 != '' ]]
do
        emailID[${#emailID[@]}]=$1
shift
done

这个emailID数组我想作为第二个参数传递给第二个脚本,我想在第二个脚本中检索数组。 有没有办法在ksh / bash中做到这一点?

只需使用${@:2} 这里解释得很完美。

并将其传递到另一个脚本:

./anotherScript "${@:2}"

当然它不会将它作为数组传递(因为你不能传递数组),但它会将该数组的所有元素作为单独的参数传递。


好的,让我们这样试试吧。 这是你的第一个脚本:

#!/bin/bash
echo "Here is my awesome first argument: $1"
var=$1 # I can assign it into a variable if I want to!
echo 'Okay, and here are my other parameters!'
for curArg in "${@:2}"; do
    echo "Some arg: $curArg"
done
myArr=("${@:2}") # I can assign it into a variable as well!

echo 'Now lets pass them into another script!'
./anotherScript 'Wheeee' "${@:2}"

这是你的另一个脚本:

#!/bin/bash
echo 'Alright! Here we can retrieve some arguments!'
echo "Here we go: $@" # that is including 'Wheeee' from the previous script. But we can use the same trick from above if we want to.

您可以使用:

arg="$1"
shift
emailID=( "$@" )

第二个赋值从剩余的参数中生成一个数组。 这些天你可能会在没有报价大约$1情况下离开; 它并不总是如此,我使用双引号来保持一致性。

然后,您可以将数组传递给第二个脚本:

second_script "${emailID[@]}"

但是,由第二个脚本决定是否将参数视为数组。 它与传递一些单独的参数没有区别。 您无法将数组与数组之前或之后的参数区分开来。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM