Writing About How I stopped worrying and learned to love Bash (part 2)
I wrote previously about the things I’ve learned about the Bash shell lately. This time I’m looking at two bits of functionality that are useful for scripts or functions with variable numbers of arguments.
Iterating over a variable number of arguments
Sometimes it’s useful to be able to iterate over the arguments of a function. This is simple if you know how many arguments there are going to be, but a little trickier if you don’t. With bash, the ‘shift’ function effectively sets the list of arguments to its tail.
Here is an example of how that works:
Which outputs:
### Forwarding all function arguments to another function
All of the arguments to a function or script can be forwarded in their entirety to another function which can be useful for function reuse, for example in the case of a generic validation function. This can be done using ${@} to refer to the function’s arguments.
This example builds on the previous one and adds a second function that forwards its arguments to the first.
Which outputs: