53

If I pass any number of arguments to a shell script that invokes a Java program internally, how can I pass second argument onwards to the Java program except the first?

./my_script.sh a b c d ....

#my_script.sh ... java MyApp b c d ... 
1

2 Answers 2

78

First use shift to "consume" the first argument, then pass "$@", i.e., the list of remaining arguments:

#my_script.sh ... shift java MyApp "$@" 
Sign up to request clarification or add additional context in comments.

4 Comments

The special parameter @ should "always" be quoted: "$@", otherwise is not different from $*. Also, should be mentioned that after the shift, if not previously saved, the first parameter is lost.
@enzotib Thanks, I've quoted $@.
Doesn't quoting it cause all the arguments to be passed as a single argument, a list of space-separated arguments? I assume not, given the popularity of this answer, but maybe you can explain.
@nilbus: $@ is a special parameter, and behaves differently from other variables. See gnu.org/software/bash/manual/html_node/Special-Parameters.html.
49

You can pass second argument onwards without using "shift" as well.

set -- 1 2 3 4 5 echo "${@:0}" echo "${@:1}" echo "${@:2}" # here 

2 Comments

does not work in sh, only bash. this is called substring expansion and has a special behaviour for @. usually it counts the characters, but for @ it counts the parameters.
I see it defined as "Substring Extraction" here: tldp.org/LDP/abs/html/string-manipulation.html. Substring Extraction ${string:position} Extracts substring from $string at $position. If the $string parameter is "*" or "@", then this extracts the positional parameters, [1] starting at $position.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.