Caution: the functionalities described here are specific to the bash interpreter, and are not supported in other interpreters, especially those that only implement functionalities defined in the POSIX norm (or when bash is running in PODIX mode).
Accessing a positional parameter indexed on the last parameter
In a shell script or function, we often need to access an argument that was
passed to it. It's fairly easy when we know its index in the list of arguments,
thanks to the variables $1
, $2
, ...
It is however also possible to access a parameter of which we know the index starting from the end of the list of parameters :
These parameters are however also accessibles through the arrays $@
et $*
.
Thanks to the functionalities specific to the bash interpreter, it is
possible, among other things, to access a paramter of which we know the index
starting from the end of the list of parameters :
{
)
}
Caution: do not forget to insert a space between the colon and the dash, to
avoid confusing bash with the ${variable:-word}
notation that represents the
use of default values.
Other similar possibilities
Reading arguments using character strings
Below are some examples where we retrieve a character string holding one or
more positional parameters (separated by the first parameter of the IFS
variable, or a space if it is unset, as it is always the case within double
quotes for arrays subscripted by *
or for $*
):
- here we initialize and print the character string
s
that will contain the last positional parameter of the functionf
:{ s=""; ; } )
- below, the string
s
will hold the last two parameters (sepated by a space):{ s=""; ; } )
Reading arguments using arrays
Below are a few examples where we initialize an array holding one or more
positional parameters (resulting from the usual expansion that takes place
within double quotes for arrays subscripted by @
, or with $@
) before
printing their elements (separated by a space):
- below,
t
represents an array with 2 positional parameters starting from the second parameter of the function, i.e. the same ast=("$2" "$3")
:
{ t=(""); ; }
)
- here,
t
is an array holding two consecutive parameters, whose first one is the third positional parameter of the function, counting backwards from the last parameter:
{ t=(""); ; }
)
- lastly, in this example,
t
will hold the five last positional parameters of the function (the array will be empty if there is less than 5 parameters to the function):
{ t=(""); ; }
)