4

In bash $@ contains all the arguments used to call the script but I am looking for a solution to remove the first one

./wrapper.sh foo bar baz ...:

 #!/bin/bash

 # call `cmd` with bar baz ... (withouyt foo one)

I just want to call cmd bar baz ...

fedorqui
  • 275,237
  • 103
  • 548
  • 598
sorin
  • 161,544
  • 178
  • 535
  • 806

3 Answers3

6

You can use shift to shift the argument array. For instance, the following code:

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

produces, when called with 1 2 3 prints 1 2 3 and then 2 3:

$ ./example.sh 1 2 3
1 2 3
2 3
Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353
  • 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:41
3

shift removes arguments from $@.

shift [n]

Shift positional parameters.

Rename the positional parameters $N+1,$N+2 ... to $1,$2 ... If N is not given, it is assumed to be 1.

Exit Status: Returns success unless N is negative or greater than $#.

choroba
  • 231,213
  • 25
  • 204
  • 289
1

Environment-variable-expansion! Is a very portable solution.

Remove the first argument: with $@

${@#"$1"}

Remove the first argument: with $*

${*#"$1"}

Remove the first and second argument: with $@

${@#"$1$2"}

Both $@ or $* will work because the result of expansion is a string.

links:
Remove a fixed prefix/suffix from a string in Bash
http://www.tldp.org/LDP/abs/html/abs-guide.html#ARGLIST

Variable expansion is portable because it is defined under gnu core-utils
Search for "Environment variable expansion" at this link:
https://www.gnu.org/software/coreutils/manual/html_node/

Michael Dimmitt
  • 826
  • 10
  • 23