Saturday, December 25, 2010

Use The Shift Command To Iterate Over Bash Positional Parameters

I was writing a script where both an array and a string needed to be passed to a bash function. As in the example below.
On the caller's side there is no problem doing that but in the function is where the magic happens.

Funcer "$var1" "${anArray[@]}"

Now in Funcer imagine that our code was as such as

Funcer ()
local hostname="$1"
local host_params=("${2@}")

Bash's interpreter will assume that our array of args has only one item and will ignore $2. You might think that using the the the statement local host_params="${2[@]}" will be copacetic but then the interpreter will show you this is very wrong. The thing you need to do is use shift to move to the next parameter as shown below.

Funcer ()
local hostname="$1"
local host_params=("${@}")
for host in ${host_params[*]} ; do

   echo -en "\"$host\","

echo '\n'

} # ---------- end of function Funcer ----------

There is more information at here and in the ABS.

No comments: