How do I forward parameters to other command in bash script?

BashCommand Line

Bash Problem Overview


Inside my bash script, I would like to parse zero, one or two parameters (the script can recognize them), then forward the remaining parameters to a command invoked in the script. How can I do that?

Bash Solutions


Solution 1 - Bash

Use the shift built-in command to "eat" the arguments. Then call the child process and pass it the "$@" argument to include all remaining arguments. Notice the quotes, they should be kept, since they cause the expansion of the argument list to be properly quoted.

Solution 2 - Bash

Bash supports subsetting parameters (see Subsets and substrings), so you can choose which parameters to process/pass like this.

  1. open new file and edit it: vim r.sh:

     echo "params only 2    : ${@:2:1}"
     echo "params 2 and 3   : ${@:2:2}"
     echo "params all from 2: ${@:2:99}"
     echo "params all from 2: ${@:2}"
    
  2. run it:

     $ chmod u+x r.sh
     $ ./r.sh 1 2 3 4 5 6 7 8 9 10
    
  3. the result is:

     params only 2    : 2
     params 2 and 3   : 2 3
     params all from 2: 2 3 4 5 6 7 8 9 10
     params all from 2: 2 3 4 5 6 7 8 9 10
    

Solution 3 - Bash

bash uses the shift command:

e.g. shifttest.sh:

#!/bin/bash
echo $1
shift
echo $1 $2

shifttest.sh 1 2 3 produces

1
2 3

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionŁukasz LewView Question on Stackoverflow
Solution 1 - BashunwindView Answer on Stackoverflow
Solution 2 - BashRobert LujoView Answer on Stackoverflow
Solution 3 - BashSteve B.View Answer on Stackoverflow