Vignesh
Vignesh

Reputation: 952

bash command line arguments into an array and subset the array based on the parameter value

I am trying to get input parameters for my bash script. testbash.sh 4 1 2 4 5 Science a p * I want to get these arguments as an array which i used $@ to acquire all of it into a array. Now based on the first argument i need to subset the rest. Here the first number is 4 so from second argument to fifth argument should be saved as an array like [1 2 4 5] and the rest of the arguments in another array.

I tried this

array=( $@ ) len=${#array[@]} args=${array[@]:0:$len-${array[1]}} echo $args

I tried this to get the first part but i get error syntax error in expression (error token is ":-4") when i ran this "testbash.sh 4 1 2 4 5 Science a p * "

Upvotes: 4

Views: 2512

Answers (1)

rici
rici

Reputation: 241881

Here's one way:

FIRST_SET=("${@:2:$1}")
REST=("${@:$(($1+2))}")

That works directly from the arguments, rather than using an intermediate array. It would be easy to use the intermediate array, in more or less the same way but remembering that array indexing starts at 0 while parameter indexing effectively starts at 1 (because parameter 0 is the command name).

Note that the quotes are important: without them, the command line arguments would be passed through glob expansion and word splitting an extra time; in effect, you lose the ability to quote command line arguments.

Upvotes: 5

Related Questions