44

If you have a list in python, and you want the elements from 2 to n can do something nice like

list[2:]

I'd like to something similar with argv in Bash. I want to pass all the elements from $2 to argc to a command. I currently have

command $2 $3 $4 $5 $6 $7 $8 $9

but this is less than elegant. Would would be the "proper" way?

Mike
  • 58,961
  • 76
  • 175
  • 221

3 Answers3

76

you can do "slicing" as well, $@ gets all the arguments in bash.

echo "${@:2}"

gets 2nd argument onwards

eg

$ cat shell.sh
#!/bin/bash
echo "${@:2}"

$ ./shell.sh 1 2 3 4
2 3 4
Michał Górny
  • 18,713
  • 5
  • 53
  • 76
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
  • 9
    You should also wrap it in double-quotes to avoid problems with spaces in arguments (e.g. `echo "${@:2}"` would work properly when called with `./shell.sh 1 2 "multi-word argument" 4 5`). – Gordon Davisson Mar 06 '10 at 19:08
  • 3
    Worth noting that this supports length as well, i.e. `"${@:start:len}"` – Dan Nov 18 '13 at 10:48
  • Can you also give a default value if `${@:2}` is empty? – Gabriel Aug 07 '15 at 21:22
4

Store $1 somewhere, then shift and use $@?

Ismail Badawi
  • 36,054
  • 7
  • 85
  • 97
4

script1.sh:

#!/bin/bash
echo "$@"

script2.sh:

#!/bin/bash
shift
echo "$@"

$ sh script1.sh 1 2 3 4
1 2 3 4 
$ sh script2.sh 1 2 3 4 
2 3 4
Tom
  • 18,685
  • 15
  • 71
  • 81
  • This is a great solution, in particular to get subcommands options! – Rémi Becheras Mar 26 '18 at 09:09
  • 1
    Please double-quote `$@` (e.g. `echo "$@"`) to avoid weird parsing. See ["I just assigned a variable, but echo $variable shows something else"](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else) and ["When should I double-quote a parameter expansion?"](https://stackoverflow.com/questions/55023461/when-should-i-double-quote-a-parameter-expansion) – Gordon Davisson Oct 06 '21 at 20:38