Var Args in Bash: Sub-arrays using array expansion modifiers

On a recent adventure into Bash scripting, I recently wanted a function which took 2 parameters (host and port) and could be modified by any number of optional parameters.

There’s a lot of ways to do this with putting arrays or shifts, but there is also a reasonably elegant way to do it. In this example I’m using cURL, which requires hostname and port number but in some cases I may want to append other options.

function varArgExample(){
    local host=$1
    local port=$2
    curl http://$host:$port "${@:3}"

The magic is the “${@:3}” variable expansion at the end. It uses the well know ${@} variable, the array of all arguments passed, but it adds the little known option to say only use the array from element 3 onwards.

If only 2 varables are passed in, “${@:3}” expands out to “” (nothing, just an empty string) without any problems, acting much like varArgs in Java 6.

Should you want to stop at a certain element in the array you can also add a second option. For example,

echo "${@:2:5}"

would expand out to the values of $2, $3 and $4. Obviously, you can also start using integer variables to control the expansion and start getting into some really complicated behaviours too.

start=3; end=6
echo "${@:$start:$end}"

2 thoughts on “Var Args in Bash: Sub-arrays using array expansion modifiers

Leave a Reply to smush moth Cancel reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s