How to pass and get array as an argument to shell

2019-07-01 23:23发布

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

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条回答
萌系小妹纸
2楼-- · 2019-07-02 00:09

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.
查看更多
smile是对你的礼貌
3楼-- · 2019-07-02 00:12

You can use:

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

The second assignment makes an array out of the remaining arguments. You might get away without the quotes around $1 these days; it was not always thus and I use double quotes for consistency.

You can then pass the array to the second script:

second_script "${emailID[@]}"

However, it is up to the second script to decide whether to treat the arguments as an array. There is no difference between that and passing a number of separate arguments. You can't distinguish the array from arguments before or after the array.

查看更多
登录 后发表回答