如何通过并获得数组作为参数传递给shell脚本

如何通过并获得数组作为参数传递给shell脚本

本文介绍了如何通过并获得数组作为参数传递给shell脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我传递多个参数的shell脚本。
我该脚本我想创建第二个参数,直到最后一个参数数组。
这我能够与下面的事 -

I am passing multiple argument to a shell script.I that script I want to create an array from 2nd argument till the last argument.This I am able to do with below -

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

这EMAILID阵列我想传递给第二个脚本的第二个参数,我想找回这第二个脚本的阵列。
有没有办法做到这一点在KSH / bash中?

This emailID array I want to pass to second script as second argument and I want to retrieve the array in this second script.Is there a way to do it in ksh/bash?

推荐答案

只需使用 $ {@:2} 。据介绍完美。

Just use ${@:2}. It is explained here perfectly.

和将它传递到另一个脚本:

And to pass it into another script:

./anotherScript "${@:2}"

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

Of course it will not pass it as array (because you cannot pass an array), but it will pass all elements of that array as individual parameters.

好吧,让我们尝试这种方式。这是你的第一个脚本:

Okay, lets try it this way. Here is your first script:

#!/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}"

这是你的另一个脚本:

And here is your another script:

#!/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.

这篇关于如何通过并获得数组作为参数传递给shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:28