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 ...
Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
cm_c
  • 531
  • 1
  • 4
  • 3

2 Answers2

78

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

#my_script.sh
...
shift
java MyApp "$@"
Bolo
  • 11,542
  • 7
  • 41
  • 60
  • 4
    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 Oct 22 '10 at 10:37
  • @enzotib Thanks, I've quoted `$@`. – Bolo Oct 22 '10 at 10:58
  • 4
    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. – Edward Anderson Aug 14 '14 at 13:17
  • 2
    @nilbus: $@ is a special parameter, and behaves differently from other variables. See https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html. – Talia Aug 05 '16 at 20:07
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
bashfu
  • 491
  • 3
  • 2
  • 11
    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. – Lesmana Oct 22 '10 at 13:46
  • I see it defined as "Substring Extraction" here: https://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.` – Ohad Schneider Jul 06 '20 at 15:15