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.
2009-10-08 13:08:20
+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
2009-10-08 13:09:12
actually "$@" is safer than $*
pixelbeat
2009-10-08 13:10:15
What's the difference?
Łukasz Lew
2009-10-08 13:14:08
@pixelbeat: Thanks, good catch. I edited. @Łukasz Lew: see the linked-to page in the manual. :) Basically, it handles quoting better.
unwind
2009-10-08 13:18:52
`$@` 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
2009-10-08 14:43:59