linuxbashpositional-parameter

bash function with three to infinitely arguments


Lets assume I have some python argparse script which I would like to kind of alias using a bash function.

Let us assume this python script takes four arguments:

--arg1
--arg2
--arg3
--arg4

What I would like to achieve is taking the first two arguments at fixed positions, and after that to infinitely add the optional arguments.

function foo()  {  python3 script.py --arg1 "$1" --arg2 "$2" "$@";  }

So something like this:

foo value1 value2 --arg3 value3 --arg4 value4

However, $@ starts counting from 1.

How can I achieve this?


Solution

  • Slice the positional arguments array after the 2nd to the rest of the list as below. Also drop the non-standard keyword function from the definition.

    foo() {  
       python3 script.py --arg1 "$1" --arg2 "$2" "${@:3:$#}"
    }
    

    Also note that the last argument to $# is optional in slicing the list. Without the same it is understood that the end is upto the final positional argument.

    Also this way of argument parsing could get tricky if more positional arguments get added or the order of the arguments gets changed. For a much more efficient argument parsing, consider using the getopts (its equivalent Python module).