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:

#!/bin/bash
function foo() {
    while test ${#} -gt 0; do
        echo "${1}"
        shift
    done
}

foo apple banana orange

Which outputs:

apple
banana
orange

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

#!/bin/bash
function foo() {
    while test ${#} -gt 0; do
        echo "${1}"
        shift
    done
}

function bar() {
    foo "${@}"
}

bar apple banana orange

Which outputs:

apple
banana
orange