How to pass vector as argument in shell script?

1

I would like to pass a JSON-style vector as an argument to a script.

Example:

#!/bin/bash

vetor[]=$1

echo ${vetor[*]}

i=0
        for nomes in ${vetor[*]}
        do
            i=$(($i+1))
            echo "Nome   $i é  $nomes"
        done

And I would like to do this:

> bash MeuScript.sh [" Joao", "Jose", "Carlos"]

Is there any way to do this? For I have to pass this structure as an argument and this vector has to be interpreted as a single argument.

    
asked by anonymous 04.09.2018 / 16:48

1 answer

1

You do not have a way to pass arrays directly to the script. One way to do this is by passing the array to a variable before it, and passing it to the script:

#!/bin/bash

vetor=("$@")

echo "${vetor[@]}"

i=0

for nomes in "${vetor[@]}"
do
    i=$(($i+1))
    echo "Nome $i é $nomes"
done

And the call would look like this:

$ nomes=('João' 'Maria' 'José')
$ bash MeuScript.sh "${nomes[@]}"
    
04.09.2018 / 19:03