views:

306

answers:

2

Inside my bash script, I would like to parse zero, one or two parameters (script can recognize them). Then forward rest of parameters to a command invoked in the script. How to do it?

A: 

bash uses the shift command:

e.g. shifttest.sh:

#!/bin/bash
echo $1
shift
echo $1 $2

shifttest.sh 1 2 3 produces

1
2 3
Steve B.
+5  A: 

Use the shift built-in command to "eat" the arguments. Then call the child process and pass it the "$@" argument to include all remaining arguments. Notice the quotes, they should be kept, since they cause the expansion of the argument list to be properly quoted.

unwind
actually "$@" is safer than $*
pixelbeat
What's the difference?
Łukasz Lew
@pixelbeat: Thanks, good catch. I edited. @Łukasz Lew: see the linked-to page in the manual. :) Basically, it handles quoting better.
unwind
`$@` essentially treats each element of the array as a quoted string - they are passed along without opportunity for expansion. It also ensures that each is seen as a separate word. This explanation along with a test script demonstrating the difference is here: http://tldp.org/LDP/abs/html/internalvariables.html#APPREF
Jefromi