Reputation: 7832
I am trying to run a bash program that takes a few command line input names, and then take an array as a command line input.
I.e.,
#!/bin/bash
name1=$1
name2=$2
my_array_input=("dog" "cat" "lion")
In this example I have name1 and name2 as input, and my_array_input is declared and set inside the script.
In my real script, I'd like to also have name1 and name2 as $1 and $2, but I'd also like to be able to take from the user a (unknown size/ variable size) my_array_input. The user could input arrays of different lengths, and with his own name of animals as he wish...
Note that all inputs should be command line inputs.
Is there a trick to do this using bash scripting?
Thanks!
Upvotes: 1
Views: 1175
Reputation: 183602
The arguments to a Bash script (or any program in Unix-like operating systems) are just a list of strings, so there's no way to do exactly what you describe.
However, you can set name1
to the first argument, name2
to the second argument, and my_array_input
to all subsequent arguments:
#!/bin/bash
name1="$1"
name2="$2"
my_array_input=("${@:3}")
If the arguments to the above script are foo bar dog cat lion
, then name1
will be foo
, name2
will be bar
, and my_array_input
will be the array (dog cat lion)
.
Upvotes: 5