view raw
swag antiswag swag antiswag - 1 year ago 28
Bash Question

How to pass in an array from a script to main(args[])

I am writing a script that grabs some input from the user. Right now I am have 3 varaibles: 2 strings and one array. I am able to pass in my 2 strings just fine to main, but I do not know how to pass in the array along with the rest.

This is what I have right now

java $myJava $var1 $var2 $array

Java's main accepts only an array of String, so var1 and var2 work just fine, but how can I pass in my array, which consists of variable number of inputs from the user? Is there a way that I can convert my array to numerous variables and then pass it into main?

Tim Tim

If $array is an actual Bash array (e.g. it was declared using declare -a array, or another Bash array creation technique) then you just want to do

java $myJava "$var1" "$var2" "${array[@]}"

That will extract the array into multiple positional arguments, so that the args array that is passed into your main will be

{ var1 , var2 ,  array[0] , array[1] , array[2] , ... }