1

How can I access the values within $@ starting from the third one? Right now I'm passing them from three to nine, but I think theres a better way:

while getopts ":n" opt "$3 $4 $5 $6 $7 $8 $9"; do

2 Answers2

2

Seems like a funky approach to arguments to me, but:

[kbrandt@kbrandt: ~/scrap] cat args
args=("$@")
echo ${args[0]}
echo ${args[@]:1:2}
echo ${args[@]:0:$#}
[kbrandt@kbrandt: ~/scrap] bash args foo bar baz biz
foo
bar baz
foo bar baz biz

I recommend you check out the FAQ Answer about command line arguments (Which basically says getopts or loop/case/shift).

Kyle Brandt
  • 84,369
  • Thanks for the answer. Is there some sort of sub-array syntax, from 3 to max? Even from 3 to 9 would be enough for my needs. – Robert Munteanu Apr 19 '10 at 14:21
  • Updated accordingly (slice of array), not to sure about what the compatibility / portability of those slices is. – Kyle Brandt Apr 19 '10 at 14:25
  • Might be funky , indeed. I'm using it to force the first two arguments to always be fixed, and then the order of the rest is not enforced. – Robert Munteanu Apr 20 '10 at 06:33
2

I assume you are using bash in this instance?

If so, you should use shift.

An example:

Contents of shift.sh:

#!/bin/bash
shift 3
echo $*

Result:

graeme@graeme:~$ ./shift.sh one two three four five six
four five six
ThatGraemeGuy
  • 15,588