4

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 * "

2
  • might have to build the array manually; in any case, please post the code of what you have already tried. Commented Jun 20, 2013 at 16:58
  • added the code which i tried Commented Jun 20, 2013 at 17:09

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

This doesnt work. FIRST_SET stores just 1 and the SECOND_SET stores nothing
saved in a test.sh file and added +x and test.sh 4 1 2 4 5 Science a p *
Actually the FIRST_SET worked. Just the SECOND_SET doesn't anything. I guess echo ${SECOND_SET[@]} is the right way to print the values to the screen right?
@Vignesh: I'd use printf; see the ideone link in my previous comment.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.