sorin
sorin

Reputation: 170548

How to remove first bash argument and pass the others to another command?

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 ...

Upvotes: 5

Views: 3427

Answers (3)

Joshua Taylor
Joshua Taylor

Reputation: 85873

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

Upvotes: 7

Michael Dimmitt
Michael Dimmitt

Reputation: 1054

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/

Upvotes: 1

choroba
choroba

Reputation: 241948

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 $#.

Upvotes: 3

Related Questions