How to pass vector as argument in shell script?

Asked

Viewed 115 times

1

I would like to pass a JSON-style vector as an argument for 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 perform so :

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

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

1 answer

1


There is no way to pass arrays directly to the script. One way to do this is to pass the array to a variable before, and pass 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 go like this:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.